Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn URL into IP address using boost::asio?

Tags:

So I need some way of turning given Protocol://URLorIP:Port string into string ip int port How to do such thing with boost ASIO and Boost Regex? Or is it possible - to get IP using C++ Net Lib (boost candidate) - notice - we do not need long connection - only IP.

So I currently use such code for parsing

#include <boost/regex.hpp>
#include <vector>
#include <string>

int main(int argc, char** argv)
{
    if (argc < 2) return 0;

    std::vector<std::string> values;
    boost::regex expression(
        //   proto                 host               port
        "^(\?:([^:/\?#]+)://)\?(\\w+[^/\?#:]*)(\?::(\\d+))\?"
        //   path                  file       parameters
        "(/\?(\?:[^\?#/]*/)*)\?([^\?#]*)\?(\\\?(.*))\?"
    );
    std::string src(argv[1]);
    if (boost::regex_split(std::back_inserter(values), src, expression))
    {
        const char* names[] = {"Protocol", "Host", "Port", "Path", "File", 
                "Parameters", NULL};
        for (int i = 0; names[i]; i++)
            printf("%s: %s\n", names[i], values[i].c_str());
    }
    return 0;
}

What shall I add to my small program to parse URL into IP?

like image 346
Rella Avatar asked Mar 30 '11 12:03

Rella


1 Answers

Remember that there may be multiple IP addresses for any one hostname, boost gives you an iterator that will go through them.

The use is fairly straightforward, add this before return 0; of your program:

std::cout << "IP addresses: \n";
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::query query(values[1], "");
for(boost::asio::ip::tcp::resolver::iterator i = resolver.resolve(query);
                            i != boost::asio::ip::tcp::resolver::iterator();
                            ++i)
{
    boost::asio::ip::tcp::endpoint end = *i;
    std::cout << end.address() << ' ';
}
std::cout << '\n';

and don't forget #include <boost/asio.hpp>

test run:

~ $ g++ -g -Wall -Wextra -pedantic -Wconversion -ansi -o test test.cc -lboost_regex -lboost_system -lboost_thread
~ $ ./test http://www.google.com:7777
Protocol: http
Host: www.google.com
Port: 7777
Path:
File:
Parameters:
IP addresses:
74.125.226.179 74.125.226.176 74.125.226.178 74.125.226.177 74.125.226.180

PS: For reference, I called

  • TCP resolver's constructor
  • query's host/service constructor with a don't-care service value of ""
  • the exception-throwing form of resolve()
  • dereferenced the iterator to get a resolver entry
  • used resolver_entry's type conversion to endpoint
  • used the TCP endpoint's address() accessor
  • used operator<< to show the address: you could use to_string() instead, if needed.
like image 73
Cubbi Avatar answered Sep 22 '22 09:09

Cubbi