Functions related to socket address parsing: inet_addr, inet_ntoa, gethostname, gethostbyname

Source: Internet
Author: User

# Include <sys/socket. h>
# Include <netdb. h> // hostent, gethostbyname gethostbyaddr
# Include <string. h> // memcpy
# Include <netinet/in. h>
# Include <ARPA/inet. h> // inet_ntop
# Include <unistd. h>
# Include <stdlib. h>
# Include <stdio. h>
Int main (void)
{
Unsigned long d;
Struct in_addr ADDR;
Char * IP = "192.168.1.11 ";
D = inet_addr (IP );
Memcpy (& ADDR, & D, 4); // although inet_addr and inet_ntoa are reciprocal functions, the values obtained using inet_addr cannot be directly used in inet_ntoa, you need to use this method to convert to the in_addr type.
Printf ("long format: % lu \ n", d );
Printf ("convert to STR: % s \ n", inet_ntoa (ADDR ));
Char host [32] = {0 };
Gethostname (host, sizeof (host ));
Printf ("host name is: % s \ n", host );
Char * BD = "www.baidu.com ";
Struct hostent * HbD;
// Gethostbyname: obtains the IP address through the domain name. This function returns a hostent structure pointer, which can be used only after further conversion.
HbD = gethostbyname (BD );
// The command h_addr_list contains garbled characters, which cannot be directly typed. You need to use the inet_ntop
Printf ("after gethostbyname: % s, % s, % d, % d, % s \ n", hBD-> h_name, * HbD-> h_aliases, hBD-> h_addrtype, hbD-> h_length, * HbD-> h_addr_list );
Char ipbd [32] = {0 };
Inet_ntop (HbD-> h_addrtype, * HbD-> h_addr_list, ipbd, sizeof (ipbd ));
Printf ("real IP is: % s \ n", ipbd );
Return 0;
}

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.