DelphiFAQ Home Search:

Determine your LOCAL IP

 

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

Another piece of code to determine your machine's local IP number -
the function GetLocalIP returns it as a string.

Note:
If you run through NAT (network address translation) then your public address can only be told by someone else like:
http://www.myip.dk/

function LWToIP(LW: LongWord): string;
begin
  Result := IntToStr(LW and $FF);
  LW := LW shr 8;
  Result := Result + '.' + IntToStr(LW and $FF);
  LW := LW shr 8;
  Result := Result + '.' + IntToStr(LW and $FF);
  LW := LW shr 8;
  Result := Result + '.' + IntToStr(LW and $FF);
end;

function TForm1.GetLocalIP: string;
var
  name, A: PChar;
  h: hostent;
  I: Integer;
begin
  GetMem(name,255);
  try
    I := GetHostName(name,255);
    if I <> 0 then
      I := wsagetlastError;
    if I <> 0 then
      StatusBar1.Panels[0].Text := 'Error: ' + IntToStr(I)
    else
    begin
      h := GetHostByName(name)^;
      if h.h_length <> 4 then Result := ''
      else
      begin
        A := h.h_addr_list^;
        I := 0;
        while (A^ <> #0) and (CompareStr(A,h.h_name) <> 0) do
        begin
          inc(I,4);
          Inc(A,4)
        end;
        if I < 4 then
        begin
          Result := h.h_name
        end
        else
        begin
          while I >= 4 do
          begin
            Dec(A,4);
            Dec(I,4);
            Result := Result + LWToIP(PLongWord(A)^) + ', ';
          end;
          Delete(Result,Length(Result)-1,2);
        end
      end
    end
  finally
    FreeMem(name)
  end
end;
You don't like the formatting? Check out SourceCoder then!
Content-type: text/html

Comments:

2007-01-19, 01:55:50
[hidden] from Ukraine  
rating
I think that better piece of code. You can easy convert it to function if you need:

var
WSAData : TWSAData;
p : PHostEnt;
Name : array [0..$FF] of Char;
begin
WSAStartup($0101, WSAData);
GetHostName(name, $FF);
p := GetHostByName(Name);
showmessage(inet_ntoa(PInAddr(p.h_addr_list^)^));
WSACleanup;
end;
2012-04-02, 05:10:32
[hidden] from Alcamo, Italy  
rating

 

 

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: