Get IP address of the current Wi-Fi access point on a iPhone?

谁说胖子不能爱 提交于 2019-11-30 16:18:29

问题


I am trying to connect from my iPhone to a socket server running on the same network on my computer. How can I get the local IP address of the computer that is running the socket server?


回答1:


#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>

- (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;
}



回答2:


Your server needs to broadcast itself using the mDNS protocol.

Then on the iPhone, you can simply use gethostbyname to get the IP address. You also have a specific API for that: DNS Service Discovery C Reference.



来源:https://stackoverflow.com/questions/3538365/get-ip-address-of-the-current-wi-fi-access-point-on-a-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!