onkelwolfram
onkelwolfram

Reputation: 31

How to get local source port from socket connect() in Linux Kernel Space?

I am manipulating the connect() function in Linux Kernel source code (net/socket.c file) and need to get the source and destination port of an established connection. The function takes a struct sockaddr __user* uservaddr parameter from which I already could get the destination port by casting it to a struct sockaddr_in. But where is the local source port stored? The function also declares a struct socket* sock, which possibly contains the data I need, but I couldn't find any variable with the source port. Any help?

Upvotes: 3

Views: 2277

Answers (2)

juis jing
juis jing

Reputation: 55

struct inet_sock *inet;
struct sock *sk = sock->sk;
inet = inet_sk(sk);
u16 post = ntohs(inet->inet_sport);

Upvotes: 1

Tgilgul
Tgilgul

Reputation: 1744

Short answer: source and dest ports can be found in struct inet_sock. You can access it from connect using:

inet = inet_sk(sock->sock)

More details: The operations allowed on sockets are defined in struct proto_ops. By following the implementation for the connect() function for TCP (in net/ipv4/tcp_ipv4.c), you can see it is implemented by tcp_v4_connect():

int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
        struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
        struct inet_sock *inet = inet_sk(sk);

and later:

struct proto tcp_prot = {
        ...
        .connect                = tcp_v4_connect,

inet->inet_sport and inet->inet_dport are used for setting/getting source and destination ports in the function above.

From a quick look I can see inet_sock is already used in socket.c, so you don't need to include any additional header files.

Hope this helps.

Upvotes: 0

Related Questions