我正在通过 JSON 检索无符号长整数形式的 IP 地址。然后我尝试将其转换回人类可读的形式,即 xxx.xxx.xxx.xxx。
我收到的 JSON 内容示例:
"ip": 704210705
我有点挣扎,因为 C 从来都不是我的强项。我收到以下 EXC 错误访问错误:
unsigned long int addr = [[user objectForKey:@"ip"] unsignedLongValue];
struct in_addr *remoteInAddr = (struct in_addr *)addr;
char *sRemoteInAddr = inet_ntoa(*remoteInAddr);
我在字符行 (3) 上收到错误。
谁能给我一些建议吗?
最佳答案
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})];
关于iphone - 在 iOS 中将 IP 地址从无符号长整型转换为点语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7190949/