Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: "GetConnectedAddress" function for SocketTCP  (Read 12185 times)

0 Members and 1 Guest are viewing this topic.

zac

  • Jr. Member
  • **
  • Posts: 60
    • View Profile
"GetConnectedAddress" function for SocketTCP
« on: January 21, 2009, 02:41:44 pm »
If connected, the function returns the IP address of the foreign host. If not, the returned IP is invalid. I know this can also be done by saving the IP of the foreign host on connection, but this can get quite hard - for example if you have an own (in my case cryptographic) session management in your server and don't have to (and don't want to) rely on a constant IP address for a client. The clients and the server are not keeping the connections alive - this is not possible for a server with possibly more than 1000 clients. You'll get in trouble updating the IP, make your storage for ips thread-safe and so on...

Code: [Select]


sf::IPAddress SocketTCP::GetConnectedAddress() const
{
if(IsValid())
{
sockaddr_in ipbuffer;
SocketHelper::LengthType len = static_cast<SocketHelper::LengthType>(sizeof(ipbuffer));

if(getpeername(mySocket,reinterpret_cast<sockaddr*>(&ipbuffer),&len) == 0)
return IPAddress(inet_ntoa(ipbuffer.sin_addr));
}
return IPAddress();
}


zac

  • Jr. Member
  • **
  • Posts: 60
    • View Profile
"GetConnectedAddress" function for SocketTCP
« Reply #1 on: January 26, 2009, 01:55:48 pm »
It should be fully portable to linux/windows in the form I posted...
getpeername has the same syntax on windows and linux (Berkeley sockets standard).
Please note that I changed the error-checking to == 0 instead of >= 0.

http://msdn.microsoft.com/en-us/library/ms738533.aspx
http://linux.die.net/man/2/getpeername