简体   繁体   English

Boost asio socket:如何获取IP,连接的端口地址?

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

I have a TCP server using boost asio. 我有一个使用boost asio的TCP服务器。 I have accepted a socket connection. 我接受了套接字连接。 How to get IP, Port of machine my server is communicating with? 如何获取IP,我的服务器正在与之通信的机器端口?

BTW: Is it possible to get info on what ip that connected server user sees my server4 machine? 顺便说一句:是否有可能获得有关连接服务器用户看到我的server4机器的IP的信息?

You can get the IP and port like this: 您可以像这样获得IP和端口:

std::string sClientIp = socket().remote_endpoint().address().to_string();
unsigned short uiClientPort = socket().remote_endpoint().port();

still if you get Bad File Descriptor error in remote_endpoint you can refer to below link. 如果你在remote_endpoint中收到Bad File Descriptor错误,你可以参考下面的链接。

http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/reference/basic_socket_acceptor/accept.html 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();

http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/reference/ip__tcp/endpoint.html 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) (编辑最新的Boost版本)

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 . 我只想提一下顶级投票答案存在一些问题: socket().remote_endpoint()可能会抛出boost::system::system_error So remember to handle the exception or your program may crash. 所以请记住处理异常或您的程序可能崩溃。 It took me many hours to debug this problem. 我花了很多时间来调试这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM