给你一段用C++Builder写的源代码,不过在Delphi中也大同!
int __fastcall GetHostIPAddress(
AnsiString *Apas_ComputerName,
AnsiString *Apas_IPAddress
)
{
struct hostent *hos_Host;
struct in_addr in_Host_addr;
char c_ComputerName[80];
char *pc_Ip,*pc_ptr;
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested=MAKEWORD(2,0);
if(!(WSAStartup(wVersionRequested,&wsaData)==0))
return -1;
if(LOBYTE(wsaData.wVersion)!=2||
HIBYTE(wsaData.wVersion)!=0)
{
WSACleanup();
return -1;
}
if(gethostname(c_ComputerName,80)==SOCKET_ERROR)
return -1;
if(!(hos_Host=gethostbyname(c_ComputerName)))
return -1;
memset((void *)&in_Host_addr,sizeof(in_Host_addr),0);
in_Host_addr.s_addr=*((unsigned long *)hos_Host->h_addr_list[0]);
if(!(pc_ptr=inet_ntoa(in_Host_addr)))
return -1;
WSACleanup();
pc_Ip=new char[strlen(pc_ptr)+1];
strcpy(pc_Ip,pc_ptr);
*Apas_ComputerName=AnsiString(hos_Host->h_name);
*Apas_IPAddress=AnsiString(pc_Ip);
return 0;
}