compu92
compu92

Reputation: 101

Covert boost::asio::ip::address_v4 to string

Currently I'm looking for a way to convert a boost::asio::ip::address_v4() to a string. Is there a way to accomplish this? The method comes from the ipv4_header.hpp on the boost website

Update: i have tried boost::asio::ip::address_v4::to_string(ipv4_hdr.source_address()), but I was unsuccessful

Upvotes: 2

Views: 5781

Answers (2)

Logan Jeon
Logan Jeon

Reputation: 1

This Works.

unsigned long ip_lb;
...
ip::address peerIp = ip::address_v4(ip_lb)
cout << peerIp.to_string

Upvotes: 0

Jesse Good
Jesse Good

Reputation: 52365

address_v4 has a member function to_string.

The function you were calling, boost::asio::ip::address_v4 source_address() const returns an address_v4 object by value. Non-static member functions must be called on objects, therefore, you can call to_string() on the object returned from the function: ipv4_hdr.source_address().to_string();. Note also the member function is marked const which allows you to call it on constant objects.

The error was for two reasons:

  1. to_string() has two overloads. One accepts zero arguments and the other accepts an boost::system::error_code reference. You were trying to pass an address_v4 object as an argument to to_string(), which is incorrect (no such overload exists).

  2. The syntax boost::asio::ip::address_v4::to_string(...) will only work if to_string() is a static member function. Since to_string() is a non-static member function you need the . dot operator to call a member function on the object instance, i.e. .to_string().

Upvotes: 4

Related Questions