如何将函数inet_ntop
(const char *)的返回值转换为string
?
编码:
string ip = inet_ntop(b->ifa_addr->sa_family,tempAddrPtr,addressOutputBuffer, sizeof(addressOutputBuffer));
总是导致segfault ...
struct ifaddrs *a;
void *tempAddrPtr = NULL;
struct ifaddrs *b;
char addressOutputBuffer[INET6_ADDRSTRLEN];
int i=0;
i=getifaddrs(&a);
cout << i;
b=a;
cout << name;
for (b = a; b; b = b->ifa_next) {
cout << b->ifa_name;
if(b->ifa_addr->sa_family == AF_INET)
tempAddrPtr = &((struct sockaddr_in *)b->ifa_addr)->sin_addr;
else
tempAddrPtr = &((struct sockaddr_in6 *)b->ifa_addr)->sin6_addr;
printf(" Internet Address: %s \n",
inet_ntop(b->ifa_addr->sa_family,
tempAddrPtr,
addressOutputBuffer,
sizeof(addressOutputBuffer)));
string ip = inet_ntop(b->ifa_addr->sa_family,tempAddrPtr,addressOutputBuffer, sizeof(addressOutputBuffer));
}
freeifaddrs(a);
最佳答案
inet_ntop返回char *,如果您的inet_ntop返回,则将正确生成字符串ip对象。突变部分是inet_ntop参数,即带有指针的参数。
一些调试提示:
1. check b is null or not
2. tempAddrPtr is valid or not
3. addressOutputBuffer is valid or not