Search code examples
socketslinux-kernelkprobe

Can one retrieve a socket's port from the Linux Kernel data type `struct sock`?


Motivation

I'm trying to write a bpftrace program to trace out when a socket is ready for reading by hooking into the kprobe sock_def_readable. I will get a struct sock to inspect. I'd like to map it back to the socket I created in user-land.

Question

How does one recover the port number from a struct sock?


Solution

  • I just expanded the definition of inet_sk ... which was merely a cast.

    #!/usr/bin/env bpftrace
    
    #include <linux/net/inet_sock.h>
    
    BEGIN
    {
        printf("network tracing");
    }
    
    kprobe:sock_def_readable
    {
      $inet_sock = (struct inet_sock *)arg0;
      printf("sock_def_readable destination port %d, source port %d \n", $inet_sock->inet_sport, $inet_sock->inet_dport);
    }