临时C字符串具有相同的地址

Ros*_*one 1 c gdb

这两行产生以下输出gdb.注意两个临时字符串的地址,first_str并且second_str具有相同的地址.这是为什么?

char *first_str = inet_ntoa(first->dest);
char *second_str = inet_ntoa(second->dest);


(gdb) p first_str
$3 = 0x7ffff7ff06d8 "54.208.71.98"
(gdb) p second_str
$4 = 0x7ffff7ff06d8 "54.208.71.98"
Run Code Online (Sandbox Code Playgroud)

first->destsecond->dest包含不同的值.

goj*_*oji 8

inet_ntoa使用静态缓冲区来实现它,所以基本上每个调用都将ascii ip地址写入同一个地方.见下文:

https://www.opensource.apple.com/source/Libc/Libc-167/net.subproj/inet_ntoa.c

char *
inet_ntoa(in)
    struct in_addr in;
{
    static char b[18];
    register char *p;

    p = (char *)∈
#define UC(b)   (((int)b)&0xff)
    (void)snprintf(b, sizeof(b),
        "%d.%d.%d.%d", UC(p[0]), UC(p[1]), UC(p[2]), UC(p[3]));
    return (b);
}
Run Code Online (Sandbox Code Playgroud)

你应该使用inet_ntop.

inet_ntop还具有支持IPv6的额外好处,任何新编写的代码都应该支持IPv6.

inet_ntop的用法:

char ip[INET_ADDRSTRLEN];
if (!inet_ntop(AF_INET, &addr.sin_addr, ip, sizeof(ip))) {
    /// do something with error
}
Run Code Online (Sandbox Code Playgroud)