在设备上更改IP地址时有没有办法注册通知?

时间:2013-12-30 07:32:04

标签: ios objective-c notifications ip

我想使用NSStream向服务器发送发送和接收信息。 我想如果我能获得ip地址,服务器可以发回信息以替换静默推送通知。

当ip地址改变时可以注册通知吗?

P.S。 我目前正在使用可达性类来在网络改变时注册通知,但如果有更好的方式它会很棒!

1 个答案:

答案 0 :(得分:0)

我认为没有直接的方法来实现这一目标,但使用

`[[NSHost currentHost] address];`

将值保存到userDefault中,每次连接时检查存储的值并获取通知

我发现这个,希望这对你有用

#include <ifaddrs.h>
#include <arpa/inet.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;

} 
相关问题