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

Martin KaFai Lau
2023-03-31T21:38:11Z

On 3/30/23 11:41 AM, Stanislav Fomichev wrote:
>> +int get_sock_port6(int sock_fd, __u16 *out_port)
>> +{
>> +    struct sockaddr_in6 addr = {};
>> +    socklen_t addr_len = sizeof(addr);
>> +    int err;
>> +
>> +    err = getsockname(sock_fd, (struct sockaddr *)&addr, &addr_len);
>> +    if (err < 0)
>> +        return err;
>> +    *out_port = addr.sin6_port;
>
> The rest of the helpers don't usually care about v4 vs v6.
> Making it work for both v4 and v6 seems trivial, so maybe let's do it?

A nit on top of this. Rename it to 'int get_local_port(int sock_fd)' such that
it is clear which port it is getting.

>
>> +
>> +    return err;
>> +}
>> diff --git a/tools/testing/selftests/bpf/network_helpers.h
>> b/tools/testing/selftests/bpf/network_helpers.h
>> index f882c691b790..2ab3b50de0b7 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_sock_port6(int sock_fd, __u16 *out_port);
>
>>   struct nstoken;
>>   /**
>> --
>> 2.34.1
>