1

I have the following code for listing the ip address of a host.

// Loop through all the linked list of address and get the ip addresses
for(p = res; p != NULL; p = p->ai_next){
    void *addr;
    string ipver;

    if(p->ai_family == AF_INET){
        // IPv4 address
        sockaddr_in *ipv4 = (sockaddr_in*)p->ai_addr;
        addr = &(ipv4->sin_addr);
        ipver = "IPv4";
    }
    else{
        // IPv6 address
        sockaddr_in6 *ipv6 = (sockaddr_in6*)p->ai_addr;
        addr = &(ipv6->sin6_addr);
        ipver = "IPv6";
    }

    // use INET6_ADDRSTRLEN becuase we need it to big enough
    // convert the ip from network(bits) to presentation(eg. 127.0.0.1)
    inet_ntop(p->ai_family, addr, const_cast<char*>(ipstr.c_str()), INET6_ADDRSTRLEN);
    // print it out
    cout << ipver <<" " << ipstr << endl;
}

The problem is with:

cout << ipver << " " << ipstr << endl;

When this line gets executed i don't get any output. But when i call ipstr.c_str(), like this:

cout << ipver <<" " << ipstr.c_str() << endl;

I do get output.

I am using GCC 4.8

4
  • Where was ipstr declared? Commented Apr 9, 2016 at 2:43
  • const_cast<char*>(ipstr.c_str()) -- yikes. When you find yourself writing this (using const_cast), stop and think hard of what you're doing. There's a very good chance it's the wrong thing. Commented Apr 9, 2016 at 2:46
  • @timrau its declared as a std::string but i did not include it Commented Apr 9, 2016 at 2:49
  • @DanMašek yeah i looked at Slava's answer and that solved it. Thanks for the advice. Commented Apr 9, 2016 at 2:52

1 Answer 1

1

You cannot modify buffer, returned by std::string::c_str() and there is a reason it returns const char * so this code:

 inet_ntop(p->ai_family, addr, const_cast<char*>(ipstr.c_str()), INET6_ADDRSTRLEN);

leads to UB. create a buffer and use it:

 char buffer[INET6_ADDRSTRLEN];
 ipstr = inet_ntop(p->ai_family, addr, buffer, INET6_ADDRSTRLEN);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.