Introducing three different approaches to get local IP address in Delphi: Winsock, TIdStack and TIdIPWatch.
1) Get local IP address by Winsock
uses Winsock; . . . function GetLocalIP: string; type TaPInAddr = array [0..10] of PInAddr; PaPInAddr = ^TaPInAddr; var phe: PHostEnt; pptr: PaPInAddr; Buffer: array [0..63] of Ansichar; i: Integer; GInitData: TWSADATA; begin WSAStartup($101, GInitData); 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; WSACleanup; end;
2) Get local IP address by TIDStack Indy class
uses IdStack; . . . function GetIP : String; begin TIdStack.IncUsage; try Result := GStack.LocalAddress; finally TIdStack.DecUsage; end; end
3) Get local IP address by TIdIpWatch Indy component
uses IdBaseComponent, IdComponent, IdIPWatch; . . . function GetLocalIp: string; var IPW: TIdIPWatch; begin IpW := TIdIPWatch.Create(nil); try if IpW.LocalIP <> '' then Result := IpW.LocalIP; finally IpW.Free; end; end;