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?
Asked
Active
Viewed 2,033 times
3

Tgilgul
- 1,614
- 1
- 20
- 35

onkelwolfram
- 31
- 3
2 Answers
1
struct inet_sock *inet;
struct sock *sk = sock->sk;
inet = inet_sk(sk);
u16 post = ntohs(inet->inet_sport);

juis jing
- 55
- 1
- 8
0
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.

Tgilgul
- 1,614
- 1
- 20
- 35