[PATCH 6/7] selftests/bpf: Add helper to get port using getsockname

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



The helper will be used to programmatically retrieve,
and pass ports in userspace and kernel selftest programs.

Suggested-by: Stanislav Fomichev <sdf@xxxxxxxxxx>
Signed-off-by: Aditi Ghag <aditi.ghag@xxxxxxxxxxxxx>
---
 tools/testing/selftests/bpf/network_helpers.c | 28 +++++++++++++++++++
 tools/testing/selftests/bpf/network_helpers.h |  1 +
 2 files changed, 29 insertions(+)

diff --git a/tools/testing/selftests/bpf/network_helpers.c b/tools/testing/selftests/bpf/network_helpers.c
index 596caa176582..7217cac762f0 100644
--- a/tools/testing/selftests/bpf/network_helpers.c
+++ b/tools/testing/selftests/bpf/network_helpers.c
@@ -427,3 +427,31 @@ void close_netns(struct nstoken *token)
 	close(token->orig_netns_fd);
 	free(token);
 }
+
+int get_socket_local_port(int family, int sock_fd, __u16 *out_port)
+{
+	socklen_t addr_len;
+	int err;
+
+	if (family == AF_INET) {
+		struct sockaddr_in addr = {};
+
+		addr_len = sizeof(addr);
+		err = getsockname(sock_fd, (struct sockaddr *)&addr, &addr_len);
+		if (err < 0)
+			return err;
+		*out_port = addr.sin_port;
+		return 0;
+	} else if (family == AF_INET6) {
+		struct sockaddr_in6 addr = {};
+
+		addr_len = sizeof(addr);
+		err = getsockname(sock_fd, (struct sockaddr *)&addr, &addr_len);
+		if (err < 0)
+			return err;
+		*out_port = addr.sin6_port;
+		return 0;
+	}
+
+	return -1;
+}
diff --git a/tools/testing/selftests/bpf/network_helpers.h b/tools/testing/selftests/bpf/network_helpers.h
index f882c691b790..ca4a147b58b8 100644
--- a/tools/testing/selftests/bpf/network_helpers.h
+++ b/tools/testing/selftests/bpf/network_helpers.h
@@ -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 family, int sock_fd, __u16 *out_port);
 
 struct nstoken;
 /**
-- 
2.34.1




[Index of Archives]     [Linux Samsung SoC]     [Linux Rockchip SoC]     [Linux Actions SoC]     [Linux for Synopsys ARC Processors]     [Linux NFS]     [Linux NILFS]     [Linux USB Devel]     [Video for Linux]     [Linux Audio Users]     [Yosemite News]     [Linux Kernel]     [Linux SCSI]


  Powered by Linux