There are two methods to obtain the IP address. The first method is to use the ioctl method of socket to read the IP address of the Local Machine. However, because this method requires the input of the interface name, such as eth0, eth1, br0, eth0.97 and so on. This is too complicated for simply obtaining the IP address of the local machine. It is easier to obtain the IP address of the Local Machine by combining the gethostname function with the gethostbyname function. The basic principle is to read the IP address that matches your host name from the file/etc/hosts.
ExampleCodeAs follows:
# Include <netdb. h>
# Include <stdio. h>
Void main (void)
{
Char buff [20];
Struct hostent * hostaddr;
Struct in_addr ADDR;
Gethostname (buff, sizeof (buff); // get the local name
Printf ("hostname = % s \ n", buff );
Hostaddr = gethostbyname (buff); // obtain the local IP Address
Memcpy (& ADDR. s_addr, hostaddr-> h_addr_list [0], sizeof (ADDR. s_addr ));
Strcpy (buff, inet_ntoa (ADDR ));
Buff [15] = 0;
Fprintf (stderr, "Local IP addres = % s \ n", buff );
}