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