Tuesday, March 9, 2010

How to get IP address

Here are two methods to get your IP address, add WinSock to uses clause.
function GetIPAddress: Integer;
var
  Buffer: array[0..255] of Char;
  RemoteHost: PHostEnt;
begin
  Winsock.GetHostName(@Buffer, 255);
  RemoteHost := Winsock.GetHostByName(Buffer);
  if RemoteHost = nil then
    Result := winsock.htonl($07000001) { 127.0.0.1 }
  else
    Result := longint(pointer(RemoteHost^.h_addr_list^)^);
    Result := Winsock.ntohl(Result);
end;// function GetIPAddress: Integer;

function GetIPAddressAsString: String;
var
  tempAddress: Integer;
  Buffer: array[0..3] of Byte absolute tempAddress;
begin
  tempAddress := GetIPAddress;
  Result := Format('%d.%d.%d.%d', [Buffer[3], Buffer[2], Buffer[1], Buffer[0]]);
end;// function GetIPAddressAsString: String;
Usage example:
procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(GetIPAddressAsString);
end;

5 comments:

  1. This code shows error when compiled in Delphi 2010.


    function GetIPAddress: Integer;
    140 var
    141 Buffer: array[0..255] of Char;
    142 RemoteHost: PHostEnt;
    143 begin
    144 Winsock.GetHostName(@Buffer, 255);
    145 RemoteHost := Winsock.GetHostByName(Buffer);

    [DCC Error] GlobalFunctions.pas(145): E2010 Incompatible types: 'Array' and 'PAnsiChar'

    ReplyDelete
  2. Yes, that's because the code above is written in Delphi 7, please replace
    Buffer: array[0..255] of Char;
    with
    Buffer: array[0..255] of AnsiChar;

    ReplyDelete
  3. Thanks for d2010 comment

    ReplyDelete
  4. That's fantastic, Thank Dorin for your help.

    ReplyDelete
  5. thanks works OK on Delphi XE.

    ReplyDelete

Blogroll(General programming and Delphi feeds)