The function of the following code is to obtain the corresponding local IP address according to the name of the incoming network card, the local net address obtained before is always 127.0.0.1 the following is the correct LAN address
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) ; }}} /span>
Linux gets the IP address of the NIC