Extracting IP Address and Port Info from sockaddr_storage
Assuming for IPv4.
After taking the address of your sockaddr_storage
or sockaddr
structure and casting it to the IPv4 version sockaddr_in
, you can then access the individual bytes of the IPv4 address.
struct sockaddr_in *sin = (struct sockaddr_in *)&their_addr;
Then you can take address of the s_addr
member which is a 32 bit value (in_addr_t
) that holds the 4 bytes of the ip address (in network byte order) and cast it to a pointer to an unsigned char
which then lets you access the individual bytes of the value.
unsigned char *ip = (unsigned char *)&sin->sin_addr.s_addr;
printf("%d %d %d %d\n", ip[0], ip[1], ip[2], ip[3]);
You want to probably use getnameinfo()
function:
int getnameinfo(const struct sockaddr *sa, socklen_t salen,
char *host, size_t hostlen,
char *serv, size_t servlen, int flags);
E.g.:
struct sockaddr_storage client_addr;
socklen_t client_len = sizeof(struct sockaddr_storage);
/* Accept client request */
int client_socket = accept(server_socket,
(struct sockaddr *)&client_addr, &client_len);
char hoststr[NI_MAXHOST];
char portstr[NI_MAXSERV];
int rc = getnameinfo((struct sockaddr *)&client_addr,
client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr),
NI_NUMERICHOST | NI_NUMERICSERV);
if (rc == 0)
printf("New connection from %s %s", hoststr, portstr);