Hostent and in_addr struct

Source: Internet
Author: User

1. The hostent data structure is as follows:
Struct hostent {
Const char * h_name; // official name of host
Char ** h_aliases; // Alias List
Short h_addrtype; // host address type
Short h_length; // length of address
Char ** h_addr_list; // list of addresses from name server
# Define h_addr h_addr_list [0] // address, for backward compatiblity
};

Typedef uint32_t in_addr_t;

Struct in_addr
{
In_addr_t s_addr;
};
Here is the details of this data structure:
Struct hostent:
H_name-the formal name of the address.
H_aliases-Null Byte-pointer to the prepared name of the address.
H_addrtype-address type; usually af_inet.
H_length-the bit length of the address.
H_addr_list-Zero-byte-host network address pointer. Network byte sequence.
The first address in h_addr-h_addr_list.
When gethostbyname () succeeds, a pointer to the hostent of the struct is returned, or a null pointer.
Here is an example:
# Include <stdio. h>
# Include <stdlib. h>
# Include <netdb. h>
Int main (void ){
Struct hostent * h;
H = gethostbyname ("www.126.com ");
If (H = NULL ){
Herror ("gethostbyname ");
Exit (1 );
}
Printf ("% s \ n", H-> h_name );
Printf ("% d \ n", H-> h_addr );
Struct in_addr * In = {H-> h_addr };
Printf ("% s \ n", inet_ntoa (* In ));
// Printf ("IP Address: % s \ n", inet_ntoa (* (struct in_addr *) H-> h_addr )));
Return exit_success;
}
When gethostbyname () is used, you cannot use perror () to print the error message (because errno is not used). You should call herror ().
The struct hostent data returned by gethostbyname.

Ii. in_addr

Struct in_addr {in_addr_t s_addr ;};

The in_addr struct is used to represent a 32-bit IPv4 address.

In_addr_t is generally a 32-bit unsigned long.

Each 8 bits represent a value in an IP address bit.

For example, 192.168.3.144 is recorded as 0xc0a80390, where C0 is 192, A8 is 168, 03 is 3, and 90 is 144.

During printing, you can call the inet_ntoa () function to convert it to the char * type.

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.