16

I have a TCP server using boost asio. I have accepted a socket connection. How to get IP, Port of machine my server is communicating with?

BTW: Is it possible to get info on what ip that connected server user sees my server4 machine?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Rella
  • 65,003
  • 109
  • 363
  • 636

4 Answers4

31

You can get the IP and port like this:

std::string sClientIp = socket().remote_endpoint().address().to_string();
unsigned short uiClientPort = socket().remote_endpoint().port();
Ralf
  • 9,405
  • 2
  • 28
  • 46
5

still if you get Bad File Descriptor error in remote_endpoint you can refer to below link.

http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/reference/basic_socket_acceptor/accept.html

"Accept a new connection and obtain the endpoint of the peer." part will be helpful to you.

You can use as below

tcp::acceptor::endpoint_type end_type;
acceptor.accept(*stream.rdbuf(), end_type);
std::string sClientIp = end_type.address().to_string();
Chirag Desai
  • 1,249
  • 1
  • 10
  • 22
2

I cannot comment on the original answer. I just want to mention that there's some problem with the top voted answer: socket().remote_endpoint() may throw boost::system::system_error. So remember to handle the exception or your program may crash. It took me many hours to debug this problem.

2

http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/reference/ip__tcp/endpoint.html

i don't have experience in it, but it looks like address and port member functions should do the trick

(edit for latest Boost version)

William Symionow
  • 748
  • 11
  • 9
fazo
  • 1,807
  • 12
  • 15