将inet_ntop的结果转换为字符串

时间:2012-11-18 05:25:29

标签: c++ string sockets inet-ntop

如何将函数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);

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

问题是你的演员:

with total as
    (select count(catergory) as totalcount, catergory as single
    from table2
    group by catergory )

select single/ totalcount from total

应该是:

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;

或C:

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