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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<span style="font-weight: bold;">uses</span> Winsock; . . . <span style="font-weight: bold;">function</span> GetMyIPs: TStringList; <span style="font-weight: bold;">type</span> TaPInAddr = <span style="font-weight: bold;">Array</span>[0..10] <span style="font-weight: bold;">of</span> PInAddr; PaPInAddr = ^TaPInAddr; <span style="font-weight: bold;">var</span> phe: PHostEnt; pptr: PaPInAddr; Buffer: <span style="font-weight: bold;">Array</span>[0..63] <span style="font-weight: bold;">of</span> <span style="font-weight: bold;">Char</span>; I: <span style="font-weight: bold;">Integer</span>; GInitData: TWSAData; IPs: TStringList; <span style="font-weight: bold;">begin</span> IPs := TStringList.Create; WSAStartup($101, GInitData); GetHostName(Buffer, SizeOf(Buffer)); phe := GetHostByName(buffer); <span style="font-weight: bold;">if</span> phe = <span style="font-weight: bold;">nil</span> <span style="font-weight: bold;">then</span> IPs.Add('No IP found') <span style="font-weight: bold;">else</span> <span style="font-weight: bold;">begin</span> pPtr := PaPInAddr(phe^.h_addr_list); I := 0; <span style="font-weight: bold;">while</span> pPtr^[I] &lt;&gt; <span style="font-weight: bold;">nil</span> <span style="font-weight: bold;">do</span> <span style="font-weight: bold;">begin</span> IPs.Add(inet_ntoa(pptr^[I]^)); Inc(I); <span style="font-weight: bold;">end</span>; <span style="font-weight: bold;">end</span>; WSACleanup; Result := IPs; <span style="font-weight: bold;">end</span>; <span style="font-weight: bold;">procedure</span> TForm1.Button1Click(Sender: <span style="font-weight: bold;">TObject</span>); <span style="font-weight: bold;">begin</span> ShowMessage(GetMyIPs.CommaText); <span style="font-weight: bold;">end</span>; |