2

我通过 JSON 检索 IP 地址作为无符号长整数。我正在尝试将其转换回人类可读的形式,即 xxx.xxx.xxx.xxx。

我在 JSON 中收到的示例:

"ip": 704210705

我有点挣扎,因为 C 从来都不是我的强项。我在下面收到 EXC Bad Access 错误:

unsigned long int addr = [[user objectForKey:@"ip"] unsignedLongValue];
struct in_addr *remoteInAddr = (struct in_addr *)addr;
char *sRemoteInAddr = inet_ntoa(*remoteInAddr);

我在 char 行 (3) 上得到错误。

谁能给我任何建议?

4

2 回答 2

5
struct in_addr a;
a.s_addr = addr;
char *remote = inet_ntoa(a);

请注意, 指向的内存remote是在 libc 中静态分配的。因此,进一步调用inet_ntoa将覆盖先前的结果。

要将字符串正确放入 obj-c 领域,请使用

NSString *str = [NSString stringWithUTF8String:remote];

或者,将所有内容放在一起:

NSString *str = [NSString stringWithUTF8String:inet_ntoa((struct in_addr){addr})];
于 2011-08-25T13:20:56.033 回答
0

Swift 版本,扩展名为.

extension UInt32 {

    public func IPv4String() -> String {

        let ip = self

        let byte1 = UInt8(ip & 0xff)
        let byte2 = UInt8((ip>>8) & 0xff)
        let byte3 = UInt8((ip>>16) & 0xff)
        let byte4 = UInt8((ip>>24) & 0xff)

        return "\(byte1).\(byte2).\(byte3).\(byte4)"
    }
}

然后

print(UInt32(704210705).IPv4String())
于 2015-08-17T07:56:22.457 回答