Home > other >  Ping program implementation in C about recvfrom() doubts
Ping program implementation in C about recvfrom() doubts

Time:10-24

I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.

I have finished writing the program, and today when I tested the ping loopback address, after sending the packet, the function recvfrom() received the "first" packet (type 8), and the second recvfrom() received the response packet (type 0).

It was later discovered that the type value for the odd times was 8 and the type value for the even times was 0.

The actual packets I caught with Wireshark have corresponding response packets each time, but the first time received by recvfrom() are the outgoing packets.

        // Send
        if (sendto(sockfd, &sendicmp, ICMP_SIZE, 0, (struct sockaddr *) &to, sizeof(to)) == -1) {
            printf("sendto() error \n");
            continue;
        }
        // Receive
        struct timeval timeout = {3, 0};//3s
        setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
        if ((n = recvfrom(sockfd, buf, BUF_SIZE, 0, (struct sockaddr *) &from, &fromlen)) < 0) {

            printf("Time out! \n");
            continue;
        }
        nreceived  ;
        if (unpack(buf, n) == -1) {
            printf("unpack() error \n");
        }

enter image description here Since the type value is not 0, I let the output is not the ICMP packet sent to me

CodePudding user response:

An ICMP type 8 control message is an echo request. A type 0 is an echo reply. Thus, it sounds like your program is receiving its own requests in addition to the replies to those requests. That is natural if you are successfully pinging a loopback address, because that's how loopback works.

It's less of an issue for TCP and UDP, because these protocols provide a concept of ports on top plain IP to distinguish between different applications communicating via the same address. ICMP does not have that, so it is the responsibility of a process receiving ICMP messages to perform its own message filtering. A ping program in particular would probably ignore incoming ICMP messages other than echo replies (type 0). It might furthermore use the second four octets of the ICMP header to distinguish replies to its own echo requests from replies to other programs running at the same time.

  • Related