Obtain the IP address of the Local Machine (General Nic) in linux

Source: Internet
Author: User
Obtain the IP address of the Local Machine (General Nic) in linux-Linux Enterprise Application-Linux server application information. For more information, see the following. Author: Star

In Unix and Linux systems, you can obtain the system IP address (gethostbyname and ioctl) in two ways)

Gethostbyname obtains the network address of the corresponding computer through domain name resolution. ioctl is a series of network functions to obtain the IP address of the local machine.

(The ioctl method is recommended. The ip address displayed in this method is the same as the ip address displayed in the ifconfig command, and can run normally on the arm board without modification. The ip address provided by gethostname () and gethostbyname () methods is inconsistent with that provided by ifconfig. You cannot [do not understand why] and cannot run properly on the arm board .)

Ioctl sample program
CODE: # include
# Include
# Include
# Include
# Include
# Include
# Include
# Include


Int main (void)
{
Int s;
Struct ifconf conf;
Struct ifreq * ifr;
Char buff [BUFSIZ];
Int num;
Int I;

S = socket (PF_INET, SOCK_DGRAM, 0 );
Conf. ifc_len = BUFSIZ;
Conf. ifc_buf = buff;

Ioctl (s, SIOCGIFCONF, & conf );
Num = conf. ifc_len/sizeof (struct ifreq );
Ifr = conf. ifc_req;

For (I = 0; I <num; I ++)
{
Struct sockaddr_in * sin = (struct sockaddr_in *) (& ifr-> ifr_addr );

Ioctl (s, SIOCGIFFLAGS, ifr );
If (ifr-> ifr_flags & IFF_LOOPBACK) = 0) & (ifr-> ifr_flags & IFF_UP ))
{
Printf ("% s (% s) \ n ",
Ifr-> ifr_name,
Inet_ntoa (sin-> sin_addr ));
}
Ifr ++;
}
}
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.