Get Local IP-Address using Boost.Asio

后端 未结 5 745
悲&欢浪女
悲&欢浪女 2020-12-05 02:20

I\'m currently searching for a portable way of getting the local IP-addresses. Because I\'m using Boost anyway I thought it would be a good idea to use Boost.Asio for this t

5条回答
  •  Happy的楠姐
    2020-12-05 02:56

    Here's a trick I learned from python network programming (google) to figure out my machine's ip address. This only works if you have an internet connection and can connect to google.com and does give me my home machine's 192.168.x.x private address.

    try {
        boost::asio::io_service netService;
        udp::resolver   resolver(netService);
        udp::resolver::query query(udp::v4(), "google.com", "");
        udp::resolver::iterator endpoints = resolver.resolve(query);
        udp::endpoint ep = *endpoints;
        udp::socket socket(netService);
        socket.connect(ep);
        boost::asio::ip::address addr = socket.local_endpoint().address();
        std::cout << "My IP according to google is: " << addr.to_string() << std::endl;
     } catch (std::exception& e){
        std::cerr << "Could not deal with socket. Exception: " << e.what() << std::endl;
    
     }
    

提交回复
热议问题