00 利用WNetEnumResource函数得到的计算机名得到IP地址

Post date: 2012/3/28 上午 08:59:55

//Win32API: // WSAStartup // WSACleanup // gethostname // gethostbyname #include <winsock2.h> #pragma comment(lib,"Ws2_32") #include <windows.h> #include <iostream> void main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(2, 2); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ MessageBox(NULL, "Wrong WinSock Version. ", "Error ", MB_OK); return; } const int iChkIpTimes = 26; int localIPnums = 0; char hostName[80]; LPHOSTENT lpHostEnt; struct in_addr addr[iChkIpTimes]; for ( int i=0; i <iChkIpTimes; i++) { memset(&addr[i], 0, sizeof(in_addr)); } if ( gethostname(hostName, sizeof(hostName)) == SOCKET_ERROR ) { MessageBox(NULL, "Can 't getting local host name. ", "Error ", MB_OK); WSACleanup(); return; } std::cout << "Local host name: " << hostName << std::endl; lpHostEnt = gethostbyname( hostName ); if ( !lpHostEnt ) { MessageBox(NULL, "Bad host lookup! ", "Error ", MB_OK); WSACleanup(); return; } for ( int i=0; i <iChkIpTimes; i++) { if ( lpHostEnt-> h_addr_list[i] == 0 ) { localIPnums = i; break; } memcpy(&addr[i], lpHostEnt-> h_addr_list[i], sizeof(in_addr)); } for ( int i=0; i <localIPnums; i++) { std::cout << "Local IP Address " << i << " : " << inet_ntoa(addr[i]) << std::endl; } if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ WSACleanup(); return; } system("pause"); }