Linux gets the ip address of the NIC, and linux gets the ip address of the NIC
The following code is used to obtain the corresponding local IP address based on the input Nic name. The obtained local network address is always 127.0.0.1 and the obtained local LAN address is correct.
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); } }}