如何以编程方式获取iphone的ip地址 [英] how to get ip address of iphone programmatically

查看:84
本文介绍了如何以编程方式获取iphone的ip地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Mongoose 在iphone中启动并运行了一个网络服务器。但问题是如何让我的iphone / ipad的IP地址让用户知道他们可以访问服务器的位置。我发现 [NSHost地址] 可以完成这项工作,但我正在为app store开发,这是未记录的方法。

I got a webserver up and running in iphone by using Mongoose. But the problem is how can I get the ip address of my iphone/ipad to let the user's know where they can access the server. I found that [NSHost addresses] can do the job but I am developing for app store and this is undocumented method.

推荐答案

#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的ip地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆