Getting IPV4 Address from sockaddr Structure

How can I extract the IP address in a string? I cannot find a link that tells me how char sa_data[14] encoded.

+41
c ip-address
Aug 14 '09 at 6:11
source share
5 answers

As soon as sockaddr discarded on sockaddr_in , it becomes the following:

 struct sockaddr_in { u_short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; 
+21
Aug 14 '09 at 6:19 06:19
source share

Just move the whole sockaddr structure to sockaddr_in . Then you can use:

 char *ip = inet_ntoa(their_addr.sin_addr) 

Get the standard ip view.

+46
Aug 14 '09 at 6:17
source share

Emil's answer is correct, but I understand that inet_ntoa deprecated, and you should use inet_ntop . If you are using IPv4, add struct sockaddr to sockaddr_in . Your code will look something like this:

 struct addrinfo *res; // populated elsewhere in your code struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr; char ipAddress[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(ipv4->sin_addr), ipAddress, INET_ADDRSTRLEN); printf("The IP address is: %s\n", ipAddress); 

Take a look at this great resource for more explanation, including how to do this for IPv6 addresses.

+22
Apr 13 '14 at 8:45
source share

inet_ntoa() works for IPv4; inet_ntop() works for both IPv4 and IPv6.

Given the input of struct sockaddr *res , here are two pieces of code:

Using inet_ntoa ()

 struct sockaddr_in *addr_in = (struct sockaddr_in *)res; char *s = inet_ntoa(addr_in->sin_addr); printf("IP address: %s\n", s); 

Using inet_ntop ()

 char *s = NULL; switch(res->sa_family) { case AF_INET: { struct sockaddr_in *addr_in = (struct sockaddr_in *)res; s = malloc(INET_ADDRSTRLEN); inet_ntop(AF_INET, &(addr_in->sin_addr), s, INET_ADDRSTRLEN); break; } case AF_INET6: { struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)res; s = malloc(INET6_ADDRSTRLEN); inet_ntop(AF_INET6, &(addr_in6->sin6_addr), s, INET6_ADDRSTRLEN); break; } default: break; } printf("IP address: %s\n", s); free(s); 
+20
Mar 19 '15 at 14:22
source share

You can use getnameinfo for Windows and for Linux .

Assuming you have a good (i.e. members have corresponding meaning) sockaddr* called pSockaddr :

 char clienthost[NI_MAXHOST]; //The clienthost will hold the IP address. char clientservice[NI_MAXSERV]; int theErrorCode = getnameinfo(pSockaddr, sizeof(*pSockaddr), clienthost, sizeof(clienthost), clientservice, sizeof(clientservice), NI_NUMERICHOST|NI_NUMERICSERV); if( theErrorCode != 0 ) { //There was an error. cout << gai_strerror(e1) << endl; }else{ //Print the info. cout << "The ip address is = " << clienthost << endl; cout << "The clientservice = " << clientservice << endl; } 
+2
02 Oct '15 at 1:00
source share



All Articles