C++ 获取本机IP地址

bool GetLocalIP(char* ip) { //1.初始化wsa WSADATA wsaData; int ret=WSAStartup(MAKEWORD(2,2),&wsaData); if (ret!=0) { return false; } //2.获取主机名 char hostname[256]; ret=gethostname(hostname,sizeof(hostname)); if (ret==SOCKET_ERROR) { return false; } //3.获取主机ip HOSTENT* host=gethostbyname(hostname); if (host==NULL) { return false; } //4.转化为char*并拷贝返回 strcpy(ip,inet_ntoa(*(in_addr*)*host->h_addr_list)); return true; } 

 

多个IP的情况:

http://blog.csdn.net/iamoyjj/archive/2011/05/29/6452837.aspx

你可能感兴趣的:(C++,socket,list,null)