Network programming in Linux environment << turn >>

Source: Internet
Author: User
Tags aliases

Today we talk about "pre-network programming". Content is miscellaneous, but all are in the network application development process often encounter problems.  

first, big, small, and network byte-order

Small-endian byte-order: Little-endian, which stores the low byte at the starting address of the memory;

Big endian byte order: Big-endian, storing high bytes in the memory of the address in fact.

For example, a digital index=0x11223344, which is stored in the byte order mode of the size end, is:

At a glance, you can see the difference between the byte order of the size end.

Another concept is the network byte order. Network byte order is a well-defined data representation format in TCP/IP, which is independent of the specific CPU type, operating system and so on, so that the data can be interpreted correctly when transferring between different hosts. The network byte order takes the big endian way. Note:The X86 series CPUs are small-endian Little-endian byte-order, which is low-byte storage low and high-byte highs.

To do this, Linux specifically provides byte conversion functions.

 unsigned long  int  htonl (unsigned Span style= "color: #0000ff;" >long  int   Hostlong) unsigned  Span style= "color: #0000ff;" >short  int  htons (unisgned short  Span style= "color: #0000ff;" >int   Hostshort) unsigned  long  Span style= "color: #0000ff;" >int  ntohl (unsigned long  int  Span style= "color: #000000;" > Netlong) unsigned  short  int  Ntohs (unsigned short  

Look at an example:

In these four conversion functions, H represents host,n on behalf of Network,s representing Short,l for long. The meaning of the htonl () function is to convert the long data on this machine into a long on the network. Several other functions have the same meaning.

That is, for the basic data type data received from the network, the first need to use Ntohl (s) to convert it to the cost of byte-order; Similarly, the basic data type data destined for a non-single section of the network is first converted to a network byte order using HTONL (s). The most common here is the IP address and port number.

Second, the IP address of the dot decimal format and the IP address of 32bit

Our common IP addresses are expressed in dotted decimal format, such as "172.18.1.231". And in the program is basically the following structure to represent an IP:

struct in_addr {         __be32     // is actually a 32bit number };

It and the dot-decimal IP address can be converted to each other through a set of APIs:

int Inet_aton (constchar *cp,struct in_addr *INP) Invalid address CP returns 0; otherwise returns non 0 Char *inet_ntoa (structin) converts a 32-bit IP address into a dotted decimal string.

The struct in_addr{} parameters required by these two functions are network byte order.

continue to see examples: 

The conversion of "192.168.11.23" to a number is 0XC0A80B17, which is the network byte order. If printing directly, then the local according to the small-endian byte order to output, the result is net addr = 170ba8c0, just as opposed to the actual. When we first convert the cost to the byte order, and then output the result is OK, that is, host addr = C0a80b17. Similarly, Inet_ntoa () is similar.         

third, the network host name and IP address of the corresponding relationship

One of the frequently encountered problems when doing network programming is to obtain an IP address based on the host name of the other, or to resolve the host name and other information in turn based on the IP address. Linux provides two common APIs:

struct hostent *gethostbyname (constChar *name); struct hostent *gethostbyaddr (constvoidintint type);

When these two functions fail, they return null and set the H_errno error variable, call Hstrerror (H_errno) or Herror ("error"), and you can get a detailed error message. The following structure is returned when successful:

structhostent {Char*h_name;/*Host name*/     Char**h_aliases;/*List of host aliases*/     intH_addrtype;/*address Type, af_inet, or other*/     intH_length;/*The number of bytes, the IPv4 address is 4 bytes*/     Char**h_addr_list;/*IP Address list, network byte order*/}#defineH_ADDR H_addr_list[0]/* back compatibility */

GetHostByName can convert a machine name (such as www.google.com) to a struct pointer, gethostbyaddr can convert a 32-bit IP address (c0a80001) to a struct pointer. For the GETHOSTBYADDR function, the type of the input parameter "addr" is determined by the parameter "type", and the current type takes only Af_inet or Af_inet6. For example, type=2 (that is, af_inet), the addr must be a struct in_addr{} type.

Continue to see examples:

#include <stdlib.h>#include<stdio.h>#include<errno.h>#include<string.h>#include<unistd.h>#include<netdb.h>#include<sys/socket.h>#include<netinet/inch.h>#include<sys/types.h>#include<arpa/inet.h>intMainintArgChar**argv) {  structHostent *host,*Host2; if(NULL = = (host = gethostbyname (argv[1])) {Herror ("Error"); return 1; } printf ("name =%s\n",host->h_name); printf ("aliases =%s\n",*host->h_aliases); printf ("Add type =%d\n",host->H_addrtype); printf ("len =%d\n",host->h_length); printf ("ip=%s\n", Inet_ntoa (* (structin_addr*) host->h_addr)); printf ("=================================\n"); structin_addr maddr; if(0= = Inet_aton (argv[2],&maddr)) {          return 0; }   Char* C = (Char*) &maddr; printf ("org =%x.%x.%x.%x\n", * (c) &0xFF, * (c+1) &0xFF, * (c+2) &0xFF, * (c+3) &0xFF); if(NULL = = (Host2 = gethostbyaddr (&maddr,4,2)) {printf ("error:%s\n", Hstrerror (H_errno)); return 1; } printf ("name =%s\n",host2->h_name); printf ("aliases =%s\n",*host2->h_aliases); printf ("Add type =%d\n",host2->H_addrtype); printf ("len =%d\n",host2->h_length); printf ("ip=%s\n", Inet_ntoa (* (structin_addr*) host2->h_addr)); return 0;}

The results of the operation are as follows:The error returned when we call GETHOSTBYADDR to get its site information based on the IP address of the home page is an "Unknown host" error, which is left to everyone to think about. This fully demonstrates that the call to the gethostbyname () function and the gethostbyaddr () function must be judged by its return value. reprinted from: Http://blog.chinaunix.net/uid-23069658-id-3271110.html

Network programming in Linux environment << turn >>

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.