Created
December 10, 2020 11:11
-
-
Save agutenkunst/b52dfb58d7de9522d82973f17e1c6772 to your computer and use it in GitHub Desktop.
Boost Asio get local ip address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <boost/asio.hpp> | |
using boost::asio::ip::udp; | |
// Build using g++ main.cpp -L /usr/include/boost -pthread | |
int main(int argc, char* argv[]) | |
{ | |
try | |
{ | |
boost::asio::io_service io_service; | |
std::string endpoint_ip_str = "192.168.0.1"; | |
auto endpoint_ip = inet_network(endpoint_ip_str.c_str()); | |
auto endpoint_port = 8000; | |
auto host_port = 8001; | |
const boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address_v4(endpoint_ip), endpoint_port); | |
boost::asio::ip::udp::socket socket(io_service, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), host_port)); | |
socket.connect(endpoint); | |
std::cerr << socket.local_endpoint() << std::endl; | |
} | |
catch (std::exception& e) | |
{ | |
std::cerr << e.what() << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With
Output: