Last active
September 29, 2020 12:08
-
-
Save talreg/1084e12d3e2077c127df0f9e836412c3 to your computer and use it in GitHub Desktop.
getting socket info
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <arpa/inet.h> | |
#include <string> | |
using std::string; | |
string getSocketIP(int socketDescriptor) | |
{ | |
string ipAddress; | |
unsigned short remotePort; // port as well if you need it | |
sockaddr address; | |
socklen_t theSize = sizeof(address); | |
const int BUFFER_LEN = 60; | |
char ipAddressBuffer[BUFFER_LEN]; | |
::getpeername(socketDescriptor, &address, &theSize); | |
switch (address.sa_family) | |
{ | |
case AF_INET: | |
inet_ntop(AF_INET, &((sockaddr_in *)&address)->sin_addr, ipAddressBuffer, BUFFER_LEN); | |
remotePort=((sockaddr_in *)&address)->sin_port; | |
ipAddress = ipAddressBuffer; | |
break; | |
case AF_INET6: | |
inet_ntop(AF_INET6, &((sockaddr_in6 *)&address)->sin6_addr, ipAddressBuffer, BUFFER_LEN); | |
ipAddress = ipAddressBuffer; | |
remotePort=((sockaddr_in6 *)&address)->sin6_port; | |
break; | |
default: | |
break; | |
} | |
return ipAddress; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment