I am trying to write a C program that sends a UDP packet to a given IP address and waits for an ICMP router response that says that the timeout has expired. It was very simple because I just want to understand the mechanism first. I need someone to check my code, giving feedback on what happened and what is missing. I am very inexperienced in C programming, but I have to do it as an assignment - doing my best to understand this ...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <netinet/ip.h> // The packet length #define PCKT_LEN 8192 // Source IP, source port, target IP, target port from the command line arguments int main(int argc, char *argv[]) { int send, recv, resp; int ttl = 1; // Time to live char buffer[PCKT_LEN]; // Destination address struct sockaddr_in dst; // ICMP Response struct msghdr icmp; memset(buffer, 0, PCKT_LEN); // Create a raw socket with UDP protocol if ((send = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { printf("Could not process socket() [send].\n"); return EXIT_FAILURE; } // ICMP Socket if ((recv = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) { printf("Could not process socket() [recv].\n"); return EXIT_FAILURE; } dst.sin_family = AF_INET; dst.sin_addr.s_addr = inet_addr("74.125.39.106"); dst.sin_port = htons(60001); // Define time to life if(setsockopt(send, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl)) < 0) { printf("Could not process setsockopt().\n"); return EXIT_FAILURE; } if(sendto(send, buffer, sizeof(buffer), 0, (struct sockaddr *) &dst, sizeof(dst)) < 0) { printf("Could not process sendto().\n"); return EXIT_FAILURE; } if((resp = recvmsg(recv, (struct msghdr *) &icmp, IP_RECVERR|MSG_ERRQUEUE)) < 0 ) { printf("Could not process recvmsg().\n"); return EXIT_FAILURE; } close(send); close(recv); return 0; }
I keep getting "Failed to process recvmsg ()." and I donβt know what else to try. I would like to receive an ICMP response and read its senders IP address.
Waiting for helpful hints.
Yours faithfully!
source share