Question

I'm writing a program to sending and receiving packages. I have not problems with sending data via ICMP protocol, but there are problems with getting few informations such as host IP or ICMP code.

I send packages via my program with code 8 ('Echo Request') (it works) and my computer receive code 0 ('Echo Reply') or code 11 ('Time Exceeded'). I checked it in Wireshark.

I don't know how to get informations about ICMP in received packages. Part of my program:

socklen_t addrlen = sizeof(connection);
if (recvfrom(sockfd, buffer, sizeof(struct iphdr) + sizeof(struct icmphdr), 0, (struct sockaddr *)&connection, &addrlen) == -1) {
    perror("recv");
} else {
    ip_reply = (struct iphdr*) buffer;
    printf("ID: %d\n", ntohs(ip_reply->id));
    printf("TTL: %d\n", ip_reply->ttl);
}

I would like to have informations about IP of received host and the ICMP code.

I know there are fields called 'saddr' and 'daddr' inside the 'iphdr' structure. But there are have '_be32' type. I don't know how to convert it to 'char*'.

Thanks in advance :)

Was it helpful?

Solution

#include <netinet/ip_icmp.h>

...
...
...
your recvfrom
...

// first, verify the ip packet contains a ICMP
if (ip_reply->protocol == 1)
{
    // ok, it contains ICMP data
    printf("Received ICMP message from IP: %s\n", inet_ntoa(connection.sin_addr));

    // make the icmphdr struct point to the right offset
    struct icmphdr *icmp = (struct icmphdr *)((uint32_t *)ip_reply + ip_reply->ihl);

    // print what you want
    printf("ICMP type: %u\n", icmp->type);
    printf("ICMP code: %u\n", icmp->code);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top