How to detect computer IP addresses

Using Winsock unit, we can determine computer IP address. If you have more network adapters, all IP addresses will be detected.

First of all, add Winsock unit to uses list. The rest is easy. Following function will determine all IP addresses of your computer and return this list as an StringList type.

uses Winsock;
.
.
.

function GetMyIPs: TStringList;
type
  TaPInAddr = Array[0..10] of PInAddr;
  PaPInAddr = ^TaPInAddr;
var
  phe: PHostEnt;
  pptr: PaPInAddr;
  Buffer: Array[0..63] of Char;
  I: Integer;
  GInitData: TWSAData;
  IPs: TStringList;
begin
  IPs := TStringList.Create;
  WSAStartup($101, GInitData);
  GetHostName(Buffer, SizeOf(Buffer));
  phe := GetHostByName(buffer);
  if phe = nil then IPs.Add('No IP found')
  else
  begin
    pPtr := PaPInAddr(phe^.h_addr_list);
    I := 0;
    while pPtr^[I] <> nil do
    begin
      IPs.Add(inet_ntoa(pptr^[I]^));
      Inc(I);
    end;
  end;
  WSACleanup;
  Result := IPs;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(GetMyIPs.CommaText);
end;

Leave a Reply