Step-by-Step Linux Network Programming-ping command Implementation Analysis

Source: Internet
Author: User
Tags socket error unpack

Let's talk about the principles of the Ping program. In fact, it's quite simple. A host system says to another host system: I love you (ICMP packets ), then, if the host believes you or wants to communicate with you, it will return the I love you (ICMP) packet as it is. well, after the source host receives this response, it will be happy, because the other host is connected to itself. If the recipient does not receive the message, or does not catch a cold, does not want to care about you, does not return this message, or does not know that the cloud is a fog, Sorry, feelings are two people's affairs.

To have a deep understanding, we need to have three points of strength. This ping is also the same. Let's take a look at the TCP/IP protocol it uses. I just said, it sends an ICMP echo request and replies a echo response message. This ICMP (Internet Control Message Protocol) is an error control mechanism provided for gateways and target hosts, report the error to the source sender when an error occurs. is a protocol at the IP layer. However, because the error report may also go through several subnets when sent to the source sender, it involves routing selection and other issues. Therefore, ICMP packets must be sent through the IP protocol. Two levels of encapsulation are required before sending ICMP datagram data: add an ICMP header to form an ICMP packet, and then add an IP header to form an IP datagram. As shown in:

IP Header
ICMP Header
ICMP Datagram

Because the IP layer protocol is a Point-to-Point Protocol rather than an end-to-end protocol, it provides a connectionless datagram service without the concept of a port, so bind () is rarely used () and connect () functions, if used, are only used to set IP addresses. The sendto () function is used to send data, and the recvfrom () function is used to receive data.

The classic masterpiece of TCP/IP, "detailed explanation of TCP/IP protocol. Volume 1" clearly tells me that the IP Header Format is as follows:

For details, Wang's lazy people all know how to flip the books mentioned above and I will not introduce them in detail. Here I will provide the data structure implementation in Linux:

struct ip  {#if __BYTE_ORDER == __LITTLE_ENDIAN    unsigned int ip_hl:4;       /* header length */    unsigned int ip_v:4;        /* version */#endif#if __BYTE_ORDER == __BIG_ENDIAN    unsigned int ip_v:4;        /* version */    unsigned int ip_hl:4;       /* header length */#endif    u_int8_t ip_tos;            /* type of service */    u_short ip_len;             /* total length */    u_short ip_id;              /* identification */    u_short ip_off;             /* fragment offset field */#define IP_RF 0x8000            /* reserved fragment flag */#define IP_DF 0x4000            /* dont fragment flag */#define IP_MF 0x2000            /* more fragments flag */#define IP_OFFMASK 0x1fff       /* mask for fragmenting bits */    u_int8_t ip_ttl;            /* time to live */    u_int8_t ip_p;              /* protocol */    u_short ip_sum;             /* checksum */    struct in_addr ip_src, ip_dst;  /* source and dest address */  };

Not to mention this. In fact, few ping programs are used:

(1) The length of the IP header IHL (Internet header length) records the length of the IP header in 4 bytes. It is the ip_hl variable of the preceding IP data structure.

(2) TTL (time to live), in seconds, indicates the maximum time for IP datagram to stay on the network. The value is set by the sender, when the value is 0, the datagram is discarded, which is the ip_ttl variable of the preceding IP data structure. ICMP messages are classified into two types: query messages and error messages. Each ICMP header contains three types: type, encoding, and checksum. Other options vary with the ICMP function. The ICMP Message format is as follows:

The ping command only uses two types of ICMP packets: "request delivery" (ICMP_Echo) and "Request Response" (ICMP_ECHOREPLY ). In Linux, it is defined as follows:

#define ICMP_ECHO   0#define ICMP_ECHOREPLY  8

In Linux, the ICMP data structure (<netinet/ip_icmp.h>) is defined as follows:

In Linux, the ICMP Data Structure struct ICMP {u_int8_t icmp_type;/* type of message, see below */u_int8_t icmp_code;/* type sub Code */u_int16_t icmp_cksum; /* ones complement checksum of struct */Union {u_char ih_pptr;/* icmp_paramprob */struct in_addr ih_gwaddr; /* gateway address */struct ih_idseq/* echo datate*/{u_int16_t icd_id; u_int16_t icd_seq;} ih_idseq; u_int32_t ih_void;/* path -- path MTU discovery (rfc1191) */struct ih_pmtu {u_int16_t ipm_void; u_int16_t ipm_nextmtu ;} ih_pmtu; struct ih_rtradv {u_int8_t irt_num_addrs; u_int8_t irt_wpa; u_int16_t irt_lifetime;} ih_rtradv;} icmp_hun; # define icmp_pptr sequence # define icmp_id sequence # define icmp_seq sequence # define icmp_void sequence # define icmp_lifetime Sequence union {struct {u_int32_t its_otime; u_int32_t its_rtime; u_int32_t its_ttime;} id_ts; struct {struct IP idi_ip;/* options and then 64 bits of data */} id_ip; struct define id_radv; u_int32_t id_mask; u_int8_t id_data [1];} interval; # define icmp_otime interval # define icmp_rtime interval # define icmp_ttime interval # define icmp_ip interval # define icmp_mask interval # define icmp_data interval };

    The information to be displayed in the ping command, including the implementation of icmp_seq and TTL, but there is still a lack of RTT round-trip time. To implement this function, an ICMP datagram can be used to carry a timestamp. Use the following function to generate a timestamp:

    # Include int gettimeofday (struct timeval * TP, void * tzp) where the timeval structure is as follows: struct timeval {long TV _sec; long TV _usec ;}

    Two timeval structures are generated by gettimeofday when messages are sent and received. The difference is the round-trip time, that is, the time difference between sending and receiving ICMP packets. The timeval structure is carried by ICMP datagram,

    The tzp pointer indicates the time zone, which is generally not used and is assigned a null value. The Ping Command provided by the system calculates the loss rate of ICMP packets by collecting statistics on all sent and received ICMP packets. To achieve this purpose, two global variables are defined: the receiving counter and the sending counter, which are used to record the numbers of ICMP packets accepted and sent. Lost count = total Sent count-total received count, lost ratio = lost count/total Sent count. The following code simulates the Ping program:

    Void statistics (INT signo) {printf ("\ n -------------------- Ping statistics ------------------- \ n"); printf ("% d packets transmitted, % d received, % d % lost \ n ", nsend, nsent ed, (nsend-nsent ed)/nsend * 100); close (sockfd); exit (1 );} /* checksum algorithm */unsigned short cal_chksum (unsigned short * ADDR, int Len) {int nleft = Len; int sum = 0; unsigned short * w = ADDR; unsigned short answer = 0;/* accumulate the binary data of the ICMP header in 2 bytes */whil E (nleft> 1) {sum + = * w ++; nleft-= 2 ;}/ * If the ICMP header is an odd number of bytes, the last byte is left. The last byte is regarded as a 2-byte data height // byte. The low byte of this 2-byte data is 0 and continues to accumulate */If (nleft = 1) {* (unsigned char *) (& answer) = * (unsigned char *) W; sum + = answer;} sum = (sum> 16) + (sum & 0 xFFFF); sum + = (sum> 16); answer = ~ SUM; return answer;}/* Set ICMP header */INT pack (INT pack_no) {int I, packsize; struct ICMP * ICMP; struct timeval * tval; ICMP = (struct ICMP *) sendpacket; ICMP-> icmp_type = ICMP_Echo; ICMP-> icmp_code = 0; ICMP-> icmp_cksum = 0; ICMP-> icmp_seq = pack_no; ICMP-> icmp_id = PID; packsize = 8 + datalen; tval = (struct timeval *) ICMP-> icmp_data; gettimeofday (tval, null ); /* record the sending time */ICMP-> icmp_cksum = cal_chksum (unsigned short *) ICMP, Packsize);/* Verification Algorithm */return packsize;}/* Send three ICMP packets */void send_packet () {int packetsize; while (nsend <max_no_packets) // send max_no_packets ICMP packets {nsend ++; packetsize = pack (nsend);/* Set ICMP header * // sendpacket as the content to be sent, which is set by pack () function setting, dest_addr is the destination address, if (sendto (sockfd, sendpacket, packetsize, 0, (struct sockaddr *) & dest_addr, sizeof (dest_addr) <0) {perror ("sendto error"); continue;} Sleep (1);/* Send an ICMP packet every second * /}}/* Receive all ICMP packets */void recv_packet () {int N, fromlen; extern int errno; signal (sigalrm, Statistics); fromlen = sizeof (from ); while (nreceived <nsend) {// alarm () is used to set the signal sigalrm to be sent to the current process alarm (max_wait_time) after the number of seconds specified by the seconds parameter ); if (n = recvfrom (sockfd, recvpacket, sizeof (recvpacket), 0, (struct sockaddr *) & from, & fromlen) <0) {If (errno = eintr) continue; perror ("recvfrom error"); continue;} gettimeofday (& tvrec V, null);/* record receipt time */If (unpack (recvpacket, n) =-1) continue; nreceived ++ ;}} /* strip the ICMP header */INT unpack (char * Buf, int Len) {int I, iphdrlen; struct IP * IP; struct ICMP * ICMP; struct timeval * tvsend; double RTT; IP = (struct IP *) BUF; // calculate the length of the IP header, that is, the length mark of the IP header multiplied by 4, the Header Length indicates the number of 4-byte characters in the header. Acceptable // the minimum value is 5, and the maximum value is 15 iphdrlen = IP-> ip_hl <2; ICMP = (struct ICMP *) (BUF + iphdrlen ); /* go beyond the IP header and point to the ICMP header */len-= iphdrlen;/* The total length of the ICMP header and ICMP datagram */If (LEN <8) /* The length less than the ICMP header is unreasonable */{printf ("ICMP packets \'s length is less than 8 \ n"); Return-1 ;} /* Make sure that the ICMP response is received */If (ICMP-> icmp_type = ICMP_ECHOREPLY) & (ICMP-> icmp_id = PID )) {tvsend = (struct timeval *) ICMP-> icmp_data; TV _sub (& tvrecv, tvsend);/* time difference between receiving and sending * /RTT = tvrecv. TV _sec * 1000 + tvrecv. TV _usec/1000;/* RTT in milliseconds * // * display related information */printf ("% d byte from % s: icmp_seq = % u TTL = % d RTT = %. 3f Ms \ n ", Len, inet_ntoa (from. sin_addr), ICMP-> icmp_seq, IP-> ip_ttl, RTT);} else return-1;} int main (INT argc, char * argv []) {struct hostent * Host; struct protoent * protocol; unsigned long inaddr = 0l; int waittime = max_wait_time; // # define max_wait_time 5 Int size = 50*1024; If (argc <2) {Printf ("Usage: % s Hostname/IP address \ n", argv [0]); exit (1) ;}// getprotobyname ("ICMP ") returns the protoent structure pointer corresponding to the given protocol name and Protocol Number. If (Protocol = getprotobyname ("ICMP") = NULL) {perror ("getprotobyname"); exit (1) ;}/ * generates the original socket that uses ICMP, this socket can only generate */If (sockfd = socket (af_inet, sock_raw, protocol-> p_proto) <0) {perror ("socket error "); exit (1);}/* revoke the root permission and set the current user permission */setuid (getuid ()); /* expand the socket receiving buffer to 50 K to reduce the possibility of receiving buffer overflow. If you accidentally ping a broadcast address or multicast address, A large number of responses */setsockopt (sockfd, sol_socket, so_rcvbuf, & size, sizeof (size); bzero (& dest_addr, sizeof (dest_addr); Limit = af_inet; /* determine whether the host name or IP address is used */If (inaddr = inet_addr (argv [1]) = inaddr_none) {If (host = gethostbyname (argv [1]) = NULL)/* is the host name */{perror ("gethostbyname error"); exit (1);} memcpy (char *) & dest_addr.sin_addr, host-> h_addr, host-> h_length);} else/* is the IP address */dest_addr.sin_addr.s_addr = inet_addr (argv [1]);/* gets the process ID of main, the identifier */PID = getpid (); printf ("Ping % s (% s): % d bytes data in ICMP packets. \ n ", argv [1], inet_ntoa (dest_addr.sin_addr), datalen); send_packet ();/* Send all ICMP packets */recv_packet (); /* receive all ICMP packets */Statistics (sigalrm);/* perform Statistics */return 0;}/* subtract two timeval structures */void TV _sub (struct timeval * Out, struct timeval * In) {If (out-> TV _usec-= In-> TV _usec) <0) {-- Out-> TV _sec; out-> TV _usec + = 1000000 ;} out-> TV _sec-= In-> TV _sec ;}

    All right, compile and run. Run the program according to the normal Ping (of course, this program is still very simple, so far it does not support loop back address 127.0.0.1 ).

    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.