我有以下用于列出主机 IP 地址的代码。
// 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;
}
问题在于:
cout << ipver << " " << ipstr << endl;
当这一行被执行时,我没有得到任何输出。 但是当我调用 ipstr.c_str() 时,像这样:
cout << ipver <<" " << ipstr.c_str() << endl;
我确实得到了输出。
我正在使用 GCC 4.8
最佳答案
您不能修改由 std::string::c_str()
返回的缓冲区,它返回 const char *
是有原因的,所以这段代码:
inet_ntop(p->ai_family, addr, const_cast<char*>(ipstr.c_str()), INET6_ADDRSTRLEN);
通往 UB。创建一个缓冲区并使用它:
char buffer[INET6_ADDRSTRLEN];
ipstr = inet_ntop(p->ai_family, addr, buffer, INET6_ADDRSTRLEN);
关于c++ - 使用 std::string 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36512089/