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.

Declaration

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

Initialization

np_t.name = "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);
netpoll_print_options(&np_t);
netpoll_setup(&np_t);
np = &np_t;

Use

char message[MESSAGE_SIZE];
sprintf(message,"%d\n",42);
int len = strlen(message);
netpoll_send_udp(np,message,len);

Hope it can help someone.

Leave a Comment