Skip to content

Instantly share code, notes, and snippets.

@agutenkunst
Created December 10, 2020 11:11
Show Gist options
  • Save agutenkunst/b52dfb58d7de9522d82973f17e1c6772 to your computer and use it in GitHub Desktop.
Save agutenkunst/b52dfb58d7de9522d82973f17e1c6772 to your computer and use it in GitHub Desktop.
Boost Asio get local ip address
#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;
}
@agutenkunst
Copy link
Author

With

g++ main.cpp -L /usr/include/boost -pthread

Output:

192.168.0.136:8001

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment