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
ipstrdeclared?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.