C creating a raw UDP packet

1.2k Views Asked by At

I am interested in creating a DNS (using UDP protocol to send it) response packet, however I found limited information how to create your own packet.

Most tutorials are like this https://opensourceforu.com/2015/03/a-guide-to-using-raw-sockets/

They use structs to fill in the fields and connect them into 1 sequence. But I am concerned that the compiler can pad the struct, making it "corrupted" (make the packet longer then it should be)

I fully know that there are struct attributes, that don't allow the compiler to pad structs, but I don't want to use them

Can anyone point me some resources on packet creation. I can use Libpcap and raw sockets

1

There are 1 best solutions below

0
hyde On

You do it like this:

// helper function to add uint32_t to a buffer
char *append_uint32(char *buf_position, uint32_t value) {
  // network protocols usually use network byte order for numbers,
  // htonl is POSIX function so you may have to make your own on other platform
  // http://pubs.opengroup.org/onlinepubs/9699919799/functions/htonl.html
  value = htonl(value);
  memcpy(buf_postion, &value, sizeof value);
  return buf_position + sizeof value;
}

// example code using the function:
// generate packet with numbers 0...9 in network byte order
void func() {
  char buf[sizeof(int32_t) * 10];
  char *bptr = buf;
  for(uint32_t i=0; i<10; ++i) {
    bptr = append_uint32(bptr, i);
  }
  // do something with buf (use malloc instead of stack if you want return it!)
}