从远程客户端获取IP地址:remote_endpoint:传输端点未连接

时间:2019-06-19 14:23:12

标签: c++ sockets ip client boost-asio

有人知道如何从套接字获取远程客户端的IP地址吗? 我已经尝试过此功能: 我尝试使用此功能:

std::string s =socket.remote_endpoint().address().to_string();    

但是即使我可以往返于客户端,也总是会收到以下错误: 抛出'boost :: exception_detail :: clone_impl>'实例后终止调用   what():remote_endpoint:传输端点未连接 ^ [[AAbandon(核心已丢弃)

有什么方法可以检索发件人的ip地址(ps:想要在发送数据之前使用它进行检查)

boost::asio::io_service io_service;
boost::asio::ip::udp::socket socket(io_service);
socket.open(boost::asio::ip::udp::v4());
socket.bind(boost::asio::ip::udp::endpoint(
boost::asio::ip::udp::v4(),port));

std::cout << "Ready to receive" << std::endl;

//information about where the packets come from
boost::asio::ip::udp::endpoint sender;
/////retrieve ip
std::string s =socket.remote_endpoint().address().to_string(); 
std::cout << "The client's ip is:" << s << std::endl;

1 个答案:

答案 0 :(得分:-1)

struct sockaddr_in sAddr;
socklen_t sLen = sizeof sAddr;
[your socket] = accept([socket to listen], (struct sockaddr *) &sAddr, &sLen);

printf("%s",inet_ntoa(sAddr.sin_addr));

用您的内容替换your socketsocket to listen