简体   繁体   中英

retrieving ip and port from a sockaddr_storage

I've got a sockaddr_storage containing the ipv4 address and port of a remote host. I haven't seen these struct s before though and I'm not sure how to cast it into a struct where I can directly retrieve IP address and port number. I've tried googling the struct but haven't found anything. Any suggestions on how to do this?

Thanks

You can cast the pointer to struct sockaddr_in * or struct sockaddr_in6 * and access the members directly, but that's going to open a can of worms about aliasing violations and miscompilation issues.

A better approach would be to pass the pointer to getnameinfo with the NI_NUMERICHOST and NI_NUMERICSERV flags to get a string representation of the address and port. This has the advantage that it supports both IPv4 and IPv6 with no additional code, and in theory supports all future address types too. You might have to cast the pointer to void * (or struct sockaddr * explicitly, if you're using C++) to pass it to getnameinfo , but this should not cause problems.

To extend an answer above and provide a code that uses getnameinfo function, check this snippet:

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);

The result is that a hoststr contains an IP address from struct sockaddr_storage and a portstr contains a port respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM