Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost asio socket: how to get IP, port address of connection?

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?

like image 893
Rella Avatar asked Mar 18 '11 13:03

Rella


3 Answers

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();
like image 81
Ralf Avatar answered Oct 23 '22 21:10

Ralf


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();
like image 4
Chirag Desai Avatar answered Oct 23 '22 21:10

Chirag Desai


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)

like image 2
fazo Avatar answered Oct 23 '22 22:10

fazo