/*************************************************************************** 功能:获取网络主机的相关信息(存储在hostent结构中) 实现:gethostbyname()/gethostbyaddr() 输入:1.主机名;2.主机ip地址;3.NULL->返回本机信息 测试输入:NULL,Leen,shenjing-pc,192.168.1.101,www.google.com,www.sina.com ***************************************************************************/ #include "../common/InitSock.h" #include <WS2TCPIP.H> int main() { CInitSock sock; //ws2_32.dll的初试化和释放 hostent* pHost; //structure to hold remote host's information,such as name,alias,ip,and so on char* hostName; //remote host name //unsigned long addr; IN_ADDR addr; while (TRUE) { printf("input host name or ip address,or 'q/Q' to quit:"); hostName = (char*)malloc(16*sizeof(char)); //fgets(hostName,16,stdin); //fgets会将末尾newline符号包含在hostName中,且末位追加NULL,最多能读取N-1个字符 gets(hostName); //末尾newline用NULL替换 // If the user input is an alpha name for the host, use gethostbyname() // If not, get host by addr (assume IPv4) if (isalpha(hostName[0])) { if ((hostName[0] == 'q') || (hostName[0] == 'Q')) { break; } // hostName[strlen(hostName) - 1] = '/0'; pHost = gethostbyname(hostName); } else { // addr = inet_addr(hostName); addr.S_un.S_addr = inet_addr(hostName); // pHost = gethostbyaddr((char*)&addr,4,AF_INET); pHost = gethostbyaddr((char*)&addr.S_un.S_addr,4,AF_INET); } if (!pHost) { int errNo = WSAGetLastError(); printf("Error:%d/n",errNo); if (errNo == 11001) { printf("Host not found./n"); } } else { //use pHost to get remote host information IN_ADDR inAddr; char* szIp; printf("--------------------------------------/n"); printf("主机名称为:%s/n",pHost->h_name); for (int i = 0;;i++) { char* p = pHost->h_addr_list[i]; //point to a 32 bits ip address if (p == NULL) { break; } memcpy(&inAddr.S_un.S_addr,p,pHost->h_length); szIp = inet_ntoa(inAddr); printf("IP[%d]:%s/n",i,szIp); } printf("--------------------------------------/n"); } } free(hostName); return 0; } 说明:CInitSock为封装了ws2_32.dll初始化和释放的类,源码如下 include <winsock2.h> #pragma comment(lib,"ws2_32.lib") class CInitSock { public: CInitSock(BYTE minoVer = 2,BYTE majorVer = 2) { WSADATA wsaData; int ir; WSAStartup(MAKEWORD(minoVer,majorVer),&wsaData); ir = WSAGetLastError(); if (ir != 0) { exit(0); } } ~CInitSock() { WSACleanup(); } public: private: };