IP地址分内网的与外网的,通过下面的VC代码可以获取本机IP(如果连接路由器,会得到两个IP地址,一个内网(192.168.1.*)的,一个外网的)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include <iostream> #include <winsock2.h> #pragma comment(lib, "WS2_32") // 链接到WS2_32.lib class CInitSock { public: CInitSock(BYTE minorVer = 2, BYTE majorVer = 0) { // 初始化WS2_32.dll WSADATA wsaData; WORD sockVersion = MAKEWORD(minorVer, majorVer); if(::WSAStartup(sockVersion, &wsaData) != 0) { exit(0); } } ~CInitSock() { ::WSACleanup(); } }; int main() { CInitSock initSocket; char szHost[256]= ""; char szIp[256] = ""; //取得本地主机名 ::gethostname(szHost,256); //通过主机名得到地址信息 hostent *pHost = ::gethostbyname(szHost); in_addr addr; for(int i = 0;;i++) { //p指向一个32位的IP地址 char *p = pHost->h_addr_list[i]; if (p == NULL) { break; } memcpy(&addr.S_un.S_addr,p,pHost->h_length); char *szIpTemp = ::inet_ntoa(addr); std::cout<<"本机IP:"<<szIpTemp<<"\n"; strcpy_s(szIp,szIpTemp); } return 0; } |
文章评论