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;
}
版权声明:本文为weixin_43448686原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。