下面这段代码的作用是根据传入的网卡名称获取相对应的本地IP地址,之前获取的本地网络地址老是127.0.0.1下面的获取的是正确的局域网地址
char* hostname_to_ip(char * ifaName ){ struct ifaddrs *ifaddr, *ifa; int family, s; char host[NI_MAXHOST]; std::string str; if (getifaddrs(&ifaddr) == -1) { // perror("getifaddrs"); //exit(EXIT_FAILURE); } for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; s=getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in),host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); if((strcmp(ifa->ifa_name,ifaName)==0)&&(ifa->ifa_addr->sa_family==AF_INET)) { if (s != 0) { // printf("getnameinfo() failed: %s\n", gai_strerror(s)); //exit(EXIT_FAILURE); } freeifaddrs(ifaddr); return host; //printf("\tInterface : <%s>\n",ifa->ifa_name ); //printf("\t Address : <%s>\n", host); } } }
时间: 2024-10-19 15:12:26