Mega Code Archive

 
Categories / Delphi / Examples
 

Determine your local ip using winsock

The code below uses the WinSock unit to lookup your local IP number. Simply call the function LocalIP - it will return your IP as a string. In a LAN, it will return your local IP number, e.g. 192.168.100.25, not your external IP number. If you run through NAT then your public address can only be told by someone else like: http://www.myip.dk/ unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, WinSock; type TForm1 = class(TForm) Label1 : TLabel; Button1: TButton; Memo1 : TMemo; procedure FormCreate(Sender: TObject); private { private declarations } public { public declarations } end; var Form1: TForm1; implementation {$R *.DFM} function LocalIP : String; type TArrayPInAddr = array [0..10] of PInAddr; PArrayPInAddr = ^ TArrayPInAddr; var phe : PHostEnt; pptr : PArrayPInAddr; Buffer : array [0..63] of char; i : integer; GInitData: TWSADATA; begin WSAStartup($101, GInitData); result := ''; GetHostName(Buffer, sizeof(Buffer)); phe := GetHostByName(Buffer); if phe=nil then begin exit end; pptr := PArrayPInAddr(phe^.h_addr_list); i := 0; while pptr^[i]<>nil do begin result := StrPas(inet_ntoa(pptr^[i]^)); Inc(i); end; WSACleanup; end; procedure TForm1.FormCreate(Sender: TObject); begin ShowMessage ('Your computer''s IP address is: '+LocalIP); end; end.