selftests/bpf: Add helper to get port using getsockname
authorAditi Ghag <aditi.ghag@isovalent.com>
Fri, 19 May 2023 22:51:56 +0000 (22:51 +0000)
committerMartin KaFai Lau <martin.lau@kernel.org>
Sat, 20 May 2023 05:44:28 +0000 (22:44 -0700)
The helper will be used to programmatically retrieve
and pass ports in userspace and kernel selftest programs.

Suggested-by: Stanislav Fomichev <sdf@google.com>
Signed-off-by: Aditi Ghag <aditi.ghag@isovalent.com>
Link: https://lore.kernel.org/r/20230519225157.760788-9-aditi.ghag@isovalent.com
Signed-off-by: Martin KaFai Lau <martin.lau@kernel.org>
tools/testing/selftests/bpf/network_helpers.c
tools/testing/selftests/bpf/network_helpers.h

index 596caa1..a105c0c 100644 (file)
@@ -427,3 +427,26 @@ void close_netns(struct nstoken *token)
        close(token->orig_netns_fd);
        free(token);
 }
+
+int get_socket_local_port(int sock_fd)
+{
+       struct sockaddr_storage addr;
+       socklen_t addrlen = sizeof(addr);
+       int err;
+
+       err = getsockname(sock_fd, (struct sockaddr *)&addr, &addrlen);
+       if (err < 0)
+               return err;
+
+       if (addr.ss_family == AF_INET) {
+               struct sockaddr_in *sin = (struct sockaddr_in *)&addr;
+
+               return sin->sin_port;
+       } else if (addr.ss_family == AF_INET6) {
+               struct sockaddr_in6 *sin = (struct sockaddr_in6 *)&addr;
+
+               return sin->sin6_port;
+       }
+
+       return -1;
+}
index f882c69..6941856 100644 (file)
@@ -56,6 +56,7 @@ int fastopen_connect(int server_fd, const char *data, unsigned int data_len,
 int make_sockaddr(int family, const char *addr_str, __u16 port,
                  struct sockaddr_storage *addr, socklen_t *len);
 char *ping_command(int family);
+int get_socket_local_port(int sock_fd);
 
 struct nstoken;
 /**