Skip to content

Instantly share code, notes, and snippets.

@jkomyno
Last active August 29, 2024 18:43
Show Gist options
  • Save jkomyno/45bee6e79451453c7bbdc22d033a282e to your computer and use it in GitHub Desktop.
Save jkomyno/45bee6e79451453c7bbdc22d033a282e to your computer and use it in GitHub Desktop.
Convert a struct sockaddr address to a string, IPv4 and IPv6
// Convert a struct sockaddr address to a string, IPv4 and IPv6:
char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen)
{
switch(sa->sa_family) {
case AF_INET:
inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),
s, maxlen);
break;
case AF_INET6:
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
s, maxlen);
break;
default:
strncpy(s, "Unknown AF", maxlen);
return NULL;
}
return s;
}
@ORParga
Copy link

ORParga commented Jul 21, 2020

You can also get the port number:

public: static wchar_t* socketaddress_to_string(sockaddr* address, wchar_t* IPString, wchar_t* PortString) {
int source = 0, dest = 0;
wchar_t byte_string[4] = { 0 };
wchar_t word_string[6] = { 0 };
for (int nByte = 2; nByte < 6; nByte++) {
_itow_s((unsigned char)address->sa_data[nByte], byte_string, 10);
source = 0;
while (byte_string[source] != 0)
{
IPString[dest] = byte_string[source]; source++; dest++;
}
if (nByte < 5)IPString[dest++] = L'.';
else IPString[dest] = 0;
}

`WORD hByte = (unsigned char)(address->sa_data[0]);`
`WORD lByte = (unsigned char)(address->sa_data[1]);`

WORD port = (hByte * 256) + lByte;
_itow_s(port, word_string, 10);
source = 0;
while (word_string[source] != 0) {
PortString[source] = word_string[source];
source++;
}
PortString[source] = 0;
return IPString;
}

@DiaoWang
Copy link

Thank you so much !

@Tachi107
Copy link

Or, even better, just call getnameinfo()

char name[INET6_ADDRSTRLEN];
char port[10];
getnameinfo(sa, sizeof(sa), name, sizeof(name), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV);
printf("%s:%s\n", name, port);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment