iphone - 在 iOS 中将 IP 地址从无符号长整型转换为点语法

标签 iphone c ios ip inet

我正在通过 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/

相关文章:

iphone - 为什么设置 UITableViewCell 颜色在 "willDisplayCell"中有效,但在 "cellForRowAtIndexPath"中无效?

不能让 printf 开心。拒绝格式字符串 "i"和 "l"

iphone - iOS 应用程序上的 OpenFeint 集成

iphone - 实现 transient 属性

iphone - Objective-C 和 iOS 中的超全局变量

解析字符缓冲区的代码

c - 什么是C中的固定地址变量

android - 使用 cordova 从应用程序中删除移动设备中存在的应用程序数据库

javascript - nw.js 签署应用程序 OSX

ios - 设置原型(prototype)单元的标识符时, Storyboard 编译失败