Sssssuppp
Sssssuppp

Reputation: 711

Set Don't Fragment flag using raw sockets for UDP

I am writing a C++ program to allow me to set the DF flag (Don't Fragment bit) using raw sockets (MacOS doesn't support setting this) before sending out UDP packets.

I am relatively new to network programming and I'm looking for resources/code examples which do this.

I searched on SO, but all answers were mostly using setsockopt() which I can't really use in my case. Most of them pointed to using raw sockets, but there was no detailed answer on how raw sockets can be used to achieve this.

I have basic understanding of raw sockets. I am looking for an implementation of this which I can't find. Can someone please direct me to a code example/snippet or explain briefly how this can be achieved using raw sockets?

Upvotes: 0

Views: 1766

Answers (1)

Barmar
Barmar

Reputation: 781078

Create the raw socket.

Enable access to the IP header by setting the IP_HDRINCL socket option:

int hdrincl=1;
if (setsockopt(fd,IPPROTO_IP,IP_HDRINCL,&hdrincl,sizeof(hdrincl))==-1) {
    die("%s",strerror(errno));
}

The flags are in the ip_off field of the struct ip header, which is declared in <netinet/ip.h>. There's a macro IP_DF for the Don't Fragment flag.

((struct ip*)&packet)->ip_off |= IP_DF;

Fill in all the rest of the fields in the IP and UDP header, and the UDP payload.

Send the packet.

Upvotes: 2

Related Questions