iphone - 如何以编程方式获取iphone的IP地址

标签 iphone objective-c ipad ip-address

我通过使用 Mongoose 在 iphone 中启动并运行了一个网络服务器.但问题是如何获取我的 iphone/ipad 的 IP 地址,让用户知道他们可以在哪里访问服务器。我发现 [NSHostaddress] 可以完成这项工作,但我正在为应用商店开发,这是未记录的方法。

最佳答案

#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/

关于iphone - 如何以编程方式获取iphone的IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6807788/

相关文章:

objective-c - 释放 GCD 调度队列属性的正确方法是什么?

iphone - tableviewcell 中的图像减慢滚动速度

ipad - 在 UISplitView 加载后以模态方式呈现 View 的问题

java - AWT/SWT 中的 iPhone 密码字段?

iphone - ios 应用程序因 XMPPMessageArchiving 而崩溃

iPhone API 可以访问短信、日历、电子邮件、通话记录吗?

iphone - TableViewSuite App 需要什么样的项目类型

objective-c - 如何用 arg 写 block 。 Swift 闭包中的 "UnsafeMutablePointer<UnsafeMutablePointer<Float>>"

ios - 由于异常内存使用,启用 CATiledLayer 的 UIView(具有 drawRect 定义的 subview )崩溃

iPhone - 如何识别我的应用程序的 iTunes 用户