Prevent packet from reaching kernel stack using PF_PACKET

60 views Asked by At
  1. I am exploring the possibility of writing a user space TCP stack using PF_PACKET, thus reusing the linux system call interface for socket creation, bind, send and receive. I am only interested in capturing packets that are destined for say TCP port 8000. How can I achieve this?

  2. With the following code I was able to get the raw IP packets delivered to my application. The problem is the packets are also received by the kernel stack which returns "Connection refused". How can I prevent the kernel from processing the packets? I have googled and found that user mode stacks are indeed possible using PF_PACKET. I have also noticed similar questions but could not find a satisfactory answer.

Thank you.

int sock;
struct sockaddr_ll srv_addr;
struct ifreq s_ifr;

sock = socket(PF_PACKET, SOCK_DGRAM, ETH_P_IP);
if (sock == -1)
    fatal_error("socket()");

char *str_devname = "lo";
strncpy (s_ifr.ifr_name, str_devname, sizeof(s_ifr.ifr_name));
int rc = ioctl(sock, SIOCGIFINDEX, &s_ifr);
if( rc == -1 ) {
  fatal_error("ioctl()");
}

memset(&srv_addr, 0, sizeof(srv_addr));
srv_addr.sll_family = AF_PACKET;
srv_addr.sll_protocol = htons(ETH_P_IP);
srv_addr.sll_ifindex = s_ifr.ifr_ifindex;   // index of the network adapter

if (bind(sock, (const struct sockaddr *)&srv_addr, sizeof(srv_addr)) < 0)
    fatal_error("bind()");
0

There are 0 answers