下面這段代碼的作用是根據傳入的網卡名稱獲取相對應的本地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); } } }