2

如何将函数的返回inet_ntop(const char *) 转换为string

编码:

string ip = inet_ntop(b->ifa_addr->sa_family,tempAddrPtr,addressOutputBuffer, sizeof(addressOutputBuffer));

总是导致段错误...

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);
4

2 回答 2

0

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
于 2012-11-18T05:31:20.767 回答
0

问题是你的铸造:

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;

应该:

tempAddrPtr = &(reinterpret_cast<struct sockaddr_in*>(b->ifa_addr)->sin_addr);
tempAddrPtr = &(reinterpret_cast<struct sockaddr_in6*>(b->ifa_addr)->sin_addr);

或 C:

tempAddrPtr = &((struct sockaddr_in*)(b->ifa_addr)->sin_addr);
tempAddrPtr = &((struct sockaddr_in6*)(b->ifa_addr)->sin_addr);
于 2020-06-18T22:17:18.977 回答