 /**//***************************************************
调试环境:VC++6.0
程序名称:host.cpp
程序功能:该程序使用网络信息获取函数取得主机的有关信息,
使用以下三个函数:
gethostname()
gethostbyname()
getprotobyname()
*************************************changshoumeng*/
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib,"ws2_32.lib")

void main()
  {
WSADATA wsaData;
int n;
char hostname[256];
hostent *pHostent;//主机信息指针
protoent *pProtoent;//主机协议指针
struct sockaddr_in sa;//本机地址信息
if(WSAStartup(MAKEWORD(2,2),&wsaData) !=0)
 {
printf("Failed to load Winsock. \n");
return ;
}
printf("--------------------\n");

if(gethostname(hostname,sizeof(hostname)) !=0)
 {
printf("gethostname() Error:%d \n",WSAGetLastError());
return;
}

printf("以下信息是由gethostname()函数取得\n ");
printf("Local host name: %s \n",hostname);
printf("-------------------\n");
pHostent =gethostbyname(hostname);//返回指定主机名的信息
if(pHostent ==NULL)
 {
printf("gethostbyname() Error: %u \n",WSAGetLastError());
return;
}
printf("以下信息由gethostbyname()函数取得\n");
printf("name:%s\n aliases:%d\n addrtype:%d\n length:%d\n",
pHostent->h_name,//名称
pHostent->h_aliases,//别名
pHostent->h_addrtype,//地址类型
pHostent->h_length );//地址长度

for(n=0;pHostent->h_addr_list[n];n++)
 {
memcpy(&sa.sin_addr.s_addr,pHostent->h_addr_list[n], pHostent->h_length);
printf("Address:%s \n",inet_ntoa(sa.sin_addr));//主机地址即IP地址
}
printf("-------------------\n");

pProtoent = getprotobyname("tcp");//返回指定协议的信息
if(pProtoent == NULL)
 {
printf("getprotobyname() Error: %u \n",WSAGetLastError());
return;
}
printf("以下信息由 getprotobyname()函数取得 \n");
printf("name:%s \n proto:%d \n",
pProtoent->p_name,//协议名
pProtoent->p_proto );//以主机顺序排列的协议号
for(n=0;pProtoent->p_aliases[n];n++)
 {
printf("aliases: %s \n",pProtoent->p_aliases[n]);
}

WSACleanup();
}
|