Obtain IP addresses in Linux

Source: Internet
Author: User
Obtain the IP address in Linux, which can be implemented by using shell or code. What I want to discuss today is to obtain the IP address of the Local Machine in C language.

After my verification, the commonly used methods of gethostname (), gethostbyname () and uname () on the network do not work. This is also evident on the uname man page.

The practical method here is to first obtain the socket and then call IOCTL to obtain its IP address.
The main code blocks and header files are as follows. # Include <sys/socket. h>
# Include <sys/IOCTL. h>
# Include <netinet/in. h>
# Include <ARPA/inet. h>
# Include <net/If. h>

Int sock_fd;
Struct my_addr;
Struct ifreq IFR;
Unsigned char * ADDR;

# Define eth_interface_name "eth0"

/** // * Get socket file descriptor */
If (sock_fd = socket (pf_inet, sock_dgram, 0) =-1 )...{
Perror ("socket ");
Exit (1 );
}

/** // * Get IP Address */
Strncpy (IFR. ifr_name, eth_interface_name, if_namesize );
IFR. ifr_name [IFNAMSIZ-1] = '/0 ';

If (IOCTL (sock_fd, siocgifaddr, & IFR) <0 )...{
Perror ("IOCTL ");
Exit (1 );
}

Memcpy (& my_addr, & IFR. ifr_addr, sizeof (my_addr ));
ADDR = inet_ntoa (my_addr.sin_addr );

After you get the ADDR, you need to know how to handle it.
In addition, if you use the inet_ntop () function to replace inet_ntoa, you can get better support for IPv6.

For more information about struct ifreq, see
Http://linux.about.com/library/cmd/blcmdl7_netdevice.htm

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.