将IP地址转换为iOS中无符号长整数的点语法

时间:2011-08-25 13:11:07

标签: iphone c ios ip inet

我正在通过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)上得到错误。

有人可以给我任何建议吗?

2 个答案:

答案 0 :(得分:5)

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

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

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

NSString *str = [NSString stringWithUTF8String:remote];

或者,把所有东西放在一起:

NSString *str = [NSString stringWithUTF8String:inet_ntoa((struct in_addr){addr})];

答案 1 :(得分:0)

Swift version, with extension

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())