DelphiFAQ Home Search:

Determine your local IP using Winsock

 

comments4 comments. Current rating: 4 stars (3 votes). Leave comments and/ or rate it.

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.
You don't like the formatting? Check out SourceCoder then!
Content-type: text/html

Comments:

2006-08-21, 15:54:39
anonymous from Canada  
rating
2009-03-20, 02:11:47
anonymous from South Africa  
rating
it seems that this program reads all the available IP Addresses and display the oldest one.
2009-04-09, 01:45:03
anonymous from United States  
rating
Awesome!
2012-11-12, 05:07:37
anonymous from United States  

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: