Sending UDP packets from the Linux Kernel

I solved my problem a few months ago. Here’s the solution I used.

The standard packet-sending API (sock_create, connect, …) cannot be used in a few contexts (interruptions). Using it in the wrong place leads to a KP.

The netpoll API is more “low-level” and works in every context. However, there are several conditions :

  • Ethernet devices
  • IP network
  • UDP only (no TCP)
  • Different computers for sending and receiving packets (You can’t send to yourself.)

Make sure to respect them, because you won’t get any error message if there’s a problem. It will just silently fail 🙂 Here’s a bit of code.


#include <linux/netpoll.h>
#define MESSAGE_SIZE 1024
#define INADDR_LOCAL ((unsigned long int)0xc0a80a54) //
#define INADDR_SEND ((unsigned long int)0xc0a80a55) //
static struct netpoll* np = NULL;
static struct netpoll np_t;

Initialization = "LRNG";
strlcpy(np_t.dev_name, "eth0", IFNAMSIZ);
np_t.local_ip = htonl(INADDR_LOCAL);
np_t.remote_ip = htonl(INADDR_SEND);
np_t.local_port = 6665;
np_t.remote_port = 6666;
memset(np_t.remote_mac, 0xff, ETH_ALEN);
np = &np_t;


char message[MESSAGE_SIZE];
int len = strlen(message);

Hope it can help someone.

Leave a Comment