I made a C program that basically sends UDP packets to a destination on Linux (Ubuntu 18.04). I am trying to send out packets larger than the network interface's MTU size (and therefore, should be fragmented). However, whenever I attempt to do so, the sendto()
function returns -1
and the packet is never sent. I am also specifying my own IP + UDP headers. From what I found online, fragmentation should be handled automatically even when passing your own IP and UDP headers. Although I wasn't able to find many others with similar issues. I was thinking that maybe I had to do a while loop and check how much data sendto()
actually sends out. However, as I said before, the function returns -1
every time only when sending packets higher than the MTU size.
I would like to note I am also not binding the socket.
Here are what my IP and UDP headers look like currently:
// Fill out IP and UDP headers.
iphdr->ihl = 5;
iphdr->frag_off = 0;
iphdr->version = 4;
iphdr->protocol = IPPROTO_UDP;
iphdr->tos = 16;
iphdr->ttl = 64;
iphdr->id = 0;
iphdr->check = 0;
iphdr->saddr = inet_addr(con->sIP);
iphdr->daddr = inet_addr(con->dIP);
iphdr->tot_len = sizeof(struct iphdr) + sizeof(struct udphdr) + len;
udphdr->uh_dport = htons(con->dPort);
udphdr->uh_sport = htons(port);
udphdr->len = htons(sizeof(struct udphdr) + len);
udphdr->check = 0;
iphdr->check = ip_csum((unsigned short *)buffer, sizeof(struct iphdr));
I also plan to calculate the UDP checksum (I was planning to do this after fixing the fragmentation issue).
Here's the code I used to create the socket:
// Create socket.
int sockfd, one = 1;
sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP);
// Check for socket error.
if (sockfd <= 0)
{
fprintf(stderr, "Socket() Error - %s\n", strerror(errno));
perror("socket");
exit(1);
}
// Assign sockfd.
con.sockfd = sockfd;
// Set socket option that tells the socket we want to send our own headers.
if (setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &one, sizeof(one)) < 0)
{
fprintf(stderr, "SetSockOpt() Error - %s\n", strerror(errno));
perror("setsockopt");
// Close socket.
close(sockfd);
exit(1);
}
I am fairly new to C and network programming. Therefore, I apologize if I am missing anything.
If you need any additional information or code, please let me know.
Any help is highly appreciated and thank you for your time!