Skip to content

Instantly share code, notes, and snippets.

@talreg
Last active September 29, 2020 12:08
Show Gist options
  • Save talreg/1084e12d3e2077c127df0f9e836412c3 to your computer and use it in GitHub Desktop.
Save talreg/1084e12d3e2077c127df0f9e836412c3 to your computer and use it in GitHub Desktop.
getting socket info
#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