char * getLocalIp() { //获取本地ip地址
char szText[256];
int iRet = gethostname(szText,256);//返回0成功,获取本机计算机名
if (iRet) {
LOG(info) << "获取本地ip失败"<<std::endl;
return NULL;
}
struct addrinfo hints,*res;
memset(&hints, 0, sizeof(addrinfo));//初始化
hints.ai_socktype = SOCK_STREAM;//TCP协议,SOCK_DGRAM udp
hints.ai_family = AF_INET;//ipv4协议
int hosttem = getaddrinfo(szText,"",&hints,&res);//0表示成功,该接口适用于ipv4和ipv6
if (hosttem) {
LOG(info) << "获取本地ip失败" << std::endl;
return NULL;
}
in_addr local_ip;
local_ip.S_un.S_addr = ((sockaddr_in*)(res->ai_addr))->sin_addr.s_addr;
char str[256];
std::cout << "ip: " << inet_ntop(AF_INET,&(local_ip.S_un.S_addr),str,256) << std::endl;//该接口适用于ipv4和ipv6
return str;
}
windows c++ 获取本地ip地址
最新推荐文章于 2021-07-25 00:37:32 发布