2006. november 20., hétfő

Obtain the actual IP address


Problem/Question/Abstract:

How to obtain the actual IP address

Answer:

Solve 1:

uses
  Winsock;

function GetLocalIPs: string;
type
  PPInAddr = ^PInAddr;
var
  wsaData: TWSAData;
  HostInfo: PHostEnt;
  HostName: array[0..255] of Char;
  Addr: PPInAddr;
begin
  Result := '';
  if WSAStartup($0102, wsaData) <> 0 then
    exit;
  try
    if gethostname(HostName, SizeOf(HostName)) <> 0 then
      exit;
    HostInfo := gethostbyname(HostName);
    if HostInfo = nil then
      exit;
    Addr := Pointer(HostInfo^.h_addr_list);
    if (Addr = nil) or (Addr^ = nil) then
      exit;
    Result := StrPas(inet_ntoa(Addr^^));
    inc(Addr);
    while Addr^ <> nil do
    begin
      Result := Result + ^M^J  + StrPas(inet_ntoa(Addr^^));
      inc(Addr);
    end;
  finally
    WSACleanup;
  end;
end;


Solve 2:

uses
  winsock;

function localIP: string;
type
  TaPInAddr = array[0..10] of PInAddr;
  PaPInAddr = ^TaPInAddr;
var
  phe: PHostEnt;
  pptr: PaPInAddr;
  Buffer: array[0..63] of char;
  I: Integer;
begin
  Result := '';
  GetHostName(Buffer, SizeOf(Buffer));
  phe := GetHostByName(buffer);
  if phe = nil then
    Exit;
  pptr := PaPInAddr(Phe^.h_addr_list);
  I := 0;
  while pptr^[I] <> nil do
  begin
    result := StrPas(inet_ntoa(pptr^[I]^));
    Inc(I);
  end;
end;


Solve 3:

You can use the following code to retrieve your local addresses:

uses
  winsock;

procedure GetAllLocalIPs(var Address: string);
type
  TaPInAddr = array[0..255] of PInAddr;
  PaPInAddr = ^TaPInAddr;
var
  pptr: PaPInAddr;
  I: Integer;
  WSAData: TWSAData;
  HostEnt: PHostEnt;
  Name: string;
begin
  Address := '';
  WSAStartup(MakeWord(1, 1), WSAData);
  SetLength(Name, 255);
  GetHostName(PChar(Name), 255);
  SetLength(Name, StrLen(PChar(Name)));
  HostEnt := GetHostByName(PChar(Name));
  with HostEnt^ do
  begin
    pptr := PaPInAddr(HostEnt^.h_addr_list);
    I := 0;
    while pptr^[I] <> nil do
    begin
      Address := Address + StrPas(inet_ntoa(pptr^[I]^)) + ';  ';
      Inc(I);
    end;
  end;
  WSACleanup;
end;

Nincsenek megjegyzések:

Megjegyzés küldése