首页 > 解决方案 > 从远程客户端获取 IP 地址:remote_endpoint:传输端点未连接

问题描述

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

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

但即使我可以从客户端 ping 到客户端,我总是会收到以下错误:在抛出 'boost::exception_detail::clone_impl >' 的实例后调用终止什么():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;

标签: c++socketsipclientboost-asio

解决方案


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 socket和。socket to listen


推荐阅读