Delphi method for obtaining machine name and IP address
---
{Get Local Machine name}
Function getlocalname (): string;
VaR
Cnamebuffer: pchar;
Clen: ^ DWORD;
Begin
Getmem (canonical buffer, 255 );
New (clen );
Clen ^: = 255;
If getcomputername (cnamebuffer, clen ^) then
Result: = cnamebuffer
Else
Result: = '';
Freemem (canonical buffer, 255 );
Dispose (clen );
End;
{Obtain the IP address based on the machine name. Add the unit: Winsock}
Function computerip (computername: string): string;
VaR Phe: phostent;
W: twsadata;
Ip_address: longint;
P: ^ longint;
Ipstr: string;
Begin
If wsastartup (2, W) <> 0 Then exit;
PHE: = gethostbyname (pchar (computername ));
If Phe <> nil then
Begin
P: = pointer (PHE ^. h_addr_list ^ );
Ip_address: = P ^;
Ip_address: = ntohl (ip_address );
Ipstr: = inttostr (ip_address SHR 24) + '.' + inttostr (ip_address SHR 16) and $ ff)
+ '.' + Inttostr (ip_address SHR 8) and $ ff) + '.' + inttostr (ip_address and $ ff );
Result: = ipstr;
End;
End;
{Obtain the local IP address and obtain the Intranet IP address or Internet IP address. Also add unit: Winsock}
Function getlocalip (internetip: Boolean): string;
Type
Tapinaddr = array [0 .. 10] of pinaddr;
Papinaddr = ^ tapinaddr;
VaR
PHE: phostent;
Pptr: papinaddr;
Buffer: array [0 .. 63] of char;
I: integer;
Ginitdata: twsadata;
IP: string;
Begin
Screen. cursor: = crhourglass;
Try
Wsastartup ($101, ginitdata );
IP: = '0. 0.0.0 ';
Gethostname (buffer, sizeof (buffer ));
PHE: = gethostbyname (buffer );
If Phe = nil then
Begin
Showmessage (IP );
Result: = IP;
Exit;
End;
Pptr: = papinaddr (PHE ^. h_addr_list );
If internetip then
Begin
I: = 0;
While pptr ^ [I] <> nil do
Begin
IP: = inet_ntoa (pptr ^ [I] ^ );
INC (I );
End;
End
Else
IP: = inet_ntoa (pptr ^ [0] ^ );
Wsacleanup;
Result: = IP address; // if the Internet is accessed, the Internet IP address is used; otherwise, the network adapter IP address is used.
Finally
Screen. cursor: = crdefault;
End;
End;
{Display example}
Procedure tform1.button1click (Sender: tobject );
Begin
Showmessage ('localname: '+ getlocalname );
Showmessage ('localip: '+ getlocalip (true ));
Showmessage ('computerip: '+ computerip (getlocalname ));
End;
-- This article comes from [TTT blog]: http://www.taoyoyo.net/ttt/post/188.html
(Note: You must retain the copyright information or indicate the source when reprinting .)