MFC obtains the Host IP Address

Source: Internet
Author: User

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

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.