Linux gets the ip address of the NIC, and linux gets the ip address of the NIC

Source: Internet
Author: User

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); } }}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.