获取本地ip(一个或多个都能取)
//在使用这个函数时先在相应的.cpp文件中添加下面的代码(头文件和库)#include <iostream> #include <string>#include "wtypes.h"#ifdef _WINDOWS_#undef _WINDOWS_#endif#pragma comment(lib, "ws2_32.lib ")
string CTaskDeal::GetLocalIpAddress(){ WORD wVersionRequested = MAKEWORD(2, 2); WSADATA wsaData; if (WSAStartup(wVersionRequested, &wsaData) != 0) return ""; char local[255] = {0}; gethostname(local, sizeof(local)); hostent* ph = gethostbyname(local); if (ph == NULL) return ""; in_addr addr; HOSTENT *host=gethostbyname(local);/*当有多个ip时,j就是所有ip的个数 inet_ntoa(*(IN_ADDR*)host->h_addr_list[i] 这里的i就是对应的每个ip for(int i=0;;i++) { cout<<inet_ntoa(*(IN_ADDR*)host->h_addr_list[i])<<endl; if(host->h_addr_list[i]+host->h_length>=host->h_name) break; }int j = i+1;*/ memcpy(&addr, ph->h_addr_list[0], sizeof(in_addr)); // 这里的0代表第一个,填1就是第二个了 string localIP; localIP.assign(inet_ntoa(addr)); WSACleanup(); return localIP;}
下面是一个简单的小实例
用vector容器将ip存起来,然后逐条打印出来
//GetIP.cpp
#include <iostream> #include <string>#include <vector>#include "wtypes.h"#ifdef _WINDOWS_#undef _WINDOWS_#endif#pragma comment(lib, "ws2_32.lib ")using namespace std;vector<string> m_IPlist;void GetLocalIpAddress() { WORD wVersionRequested = MAKEWORD(2, 2); WSADATA wsaData; if (WSAStartup(wVersionRequested, &wsaData) != 0) {return;} char local[255] = {0}; gethostname(local, sizeof(local)); hostent* ph = gethostbyname(local); if (ph == NULL){return ;}in_addr addr; HOSTENT *host=gethostbyname(local); string localIP; //当有多个ip时,j就是所有ip的个数 inet_ntoa(*(IN_ADDR*)host->h_addr_list[i] 这里的i就是对应的每个ip for(int i=0;;i++) {memcpy(&addr, ph->h_addr_list[i], sizeof(in_addr)); // localIP=inet_ntoa(addr); m_IPlist.push_back(localIP);if(host->h_addr_list[i]+host->h_length>=host->h_name) {break; //如果到了最后一条}} WSACleanup(); vector<string>::iterator it;for (it = m_IPlist.begin();it != m_IPlist.end();it++){cout<<it->c_str()<<endl; }return;} int main(){GetLocalIpAddress();return 0;}