fire010g
(Sam Chou)
December 30, 2019, 6:16am
1
I was trying to get the client address by modifying the dtls example code.
However, I always get the 0.0.0.0 did I do anything wrong?
if( ( ret = mbedtls_net_accept( &listen_fd, &client_fd,
client_ip, sizeof( client_ip ), &cliip_len ) ) != 0 )
{
printf( " failed\n ! mbedtls_net_accept returned %d\n\n", ret );
goto exit;
}
unsigned char bytes[4];
bytes[0] = *client_ip & 0xFF;
bytes[1] = (*client_ip >> 8) & 0xFF;
bytes[2] = (*client_ip >> 16) & 0xFF;
bytes[3] = (*client_ip >> 24) & 0xFF;
printf(“%d.%d.%d.%d\n”, bytes[3], bytes[2], bytes[1], bytes[0]);
roneld01
(Ron Eldor)
December 30, 2019, 12:07pm
2
HI @fire010g
Thank you for your interest in Mbed TLS.
All you need to do is get the bytes in client_ip
(for IPv4):
printf("%d.%d.%d.%d\n", client_ip[0], client_ip[1], client_ip[2], client_ip[3]);
Note that client_ip
is a byte array, so *client_ip
will return client_ip[0]
, and then shifting it will always return 0
. client_ip[0]
is probably 0
in your case.
If you wish to use bitwise operation, for portability to different architectures, please try the following:
bytes[0] = *(uint32_t*)client_ip & 0xFF;
bytes[1] = (*(uint32_t*)client_ip >> 8) & 0xFF;
bytes[2] = (*(uint32_t*)client_ip >> 16) & 0xFF;
bytes[3] = (*(uint32_t*)client_ip >> 24) & 0xFF;
Regards,
Mbed TLS Support
Ron
fire010g
(Sam Chou)
December 31, 2019, 9:19am
3
Oh god, turns out example program using IPV6 instead of IPV4, after enable FORCE_IPV4 I can get the correct IP address.
1 Like
dbaarda
(Donovan Baarda)
June 10, 2021, 4:20pm
4
I’ve just been through this myself, and the best portable code for getting the address in text format is;
#include <arpa/inet.h>
int err;
mbedtls_net_context socket;
char addr[16];
size_t len;
char ip[INET6_ADDRSTRLEN];
if ((err=mbedtls_net_accept(&server->socket, &socket, addr, sizeof(addr), &len)))
return err;
if (!inet_ntop(len == 4 ? AF_INET : AF_INET6, addr, ip, sizeof(ip)))
strcpy(ip, "<unknown>");
This will work for IPv4 and IPv6 addresses.