运行环境:VS2008,win7,代码来源于MSDN,相关函数可以查看MSDN中的函数定义。。
代码如下:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <windows.h>
#pragma comment(lib, "ws2_32.lib") int main(int argc, char **argv)
{ //-----------------------------------------
// Declare and initialize variables
WSADATA wsaData;
int iResult; DWORD dwError;
int i = ; struct hostent *remoteHost;
char *host_name;
struct in_addr addr; char **pAlias;
iResult = WSAStartup(MAKEWORD(, ), &wsaData);
if (iResult != ) {
printf("WSAStartup failed: %d\n", iResult);
return ;
} host_name = new char[];
int index = gethostname(host_name,strlen(host_name));
if ( != index)
{
printf("Error\n");
} printf("Calling gethostbyname with %s\n", host_name);
remoteHost = gethostbyname(host_name); if (remoteHost == NULL) {
dwError = WSAGetLastError();
if (dwError != ) {
if (dwError == WSAHOST_NOT_FOUND) {
printf("Host not found\n");
return ;
} else if (dwError == WSANO_DATA) {
printf("No data record found\n");
return ;
} else {
printf("Function failed with error: %ld\n", dwError);
return ;
}
}
} else {
printf("Function returned:\n");
printf("\tOfficial name: %s\n", remoteHost->h_name);
for (pAlias = remoteHost->h_aliases; *pAlias != ; pAlias++) {
printf("\tAlternate name #%d: %s\n", ++i, *pAlias);
}
printf("\tAddress type: ");
switch (remoteHost->h_addrtype) {
case AF_INET:
printf("AF_INET\n");
break;
case AF_NETBIOS:
printf("AF_NETBIOS\n");
break;
default:
printf(" %d\n", remoteHost->h_addrtype);
break;
}
printf("\tAddress length: %d\n", remoteHost->h_length); i = ;
if (remoteHost->h_addrtype == AF_INET)
{
while (remoteHost->h_addr_list[i] != ) {
addr.s_addr = *(u_long *) remoteHost->h_addr_list[i++];
printf("\tIP Address #%d: %s\n", i, inet_ntoa(addr));
}
}
else if (remoteHost->h_addrtype == AF_NETBIOS)
{
printf("NETBIOS address was returned\n");
}
} return ;
}