我用Mongoose在iphone上安装并运行了一个Web服务器.但问题是,我如何获得iphone/ipad的ip地址,让用户知道他们可以在哪里访问服务器.我发现[NSHost addresses]可以完成这项工作,但我正在为app store开发,这是一种没有文档记录的方法.

推荐答案

#include <ifaddrs.h>
#include <arpa/inet.h>

// Get the INTERNAL ip address

- (NSString *)getIPAddress {

    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

                }

            }

            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;

} 

https://web.archive.org/web/20160527165909/http://www.makebetterthings.com/iphone/how-to-find-ip-address-of-iphone/

Objective-c相关问答推荐

Xcode 的任何 ReSharper 类似功能?

防止同时多个按钮

如何在 iOS Objective-C 头文件中将函数标记为已弃用?

负数的奇怪 Objective-C Mod 行为

如何获取 NSArray 的最后一个对象

NSInternalInconsistencyException: '无效参数不满足: !stayUp || CLClientIsBackgroundable(内部->fClient)'

UITableView - Select 了哪一行?

在 iOS 和 Mac OS X 应用程序中使用 C++

如何删除 xcode 5 中的旧配置文件?

如何判断字符串是否仅包含目标C中的字母数字字符?

如何从 RGBA 创建 UIColor?

何时应该使用 initWithNibName 初始化视图控制器?

iOS6:supportedInterfaceOrientations 不起作用(被调用但界面仍然旋转)

主队列上的 dispatch_sync 与 dispatch_async

在我滚动之前,数据不会加载到 UITableView 中

通过将另一个字符串重复给定次数来创建 NSString

点击手势识别器 - 哪个对象被点击了?

如何让 UITextView 检测网站、邮件和电话号码的链接

目标 C:读取文本文件

找出窗口中的 UIBarButtonItem 框架?