国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

IOS中如何獲取手機的當前IP

2019-11-14 18:09:34
字體:
來源:轉載
供稿:網友

網上有許多類似的帖子、在搜索了資料以后、覺得下面的方法是最簡單的、

使用的時候直接把類方法拖到自己新建的分類中就行、

.h文件

#import <Foundation/Foundation.h>

@interface NSObject (Getip)

+ (NSString *)deviceIPAdress;

@end

.m文件

#import "NSObject+GetIP.h"

#include <ifaddrs.h>

#include <arpa/inet.h>

上面的兩個頭文件一定要導入


@implementation NSObject (GetIP)

+ (NSString *)deviceIPAdress {
    NSString *address = @"an error occurred when obtaining ip address";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    success = getifaddrs(&interfaces);
    
    if (success == 0) { // 0 表示獲取成功
        
        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;
        }
    }
    
    freeifaddrs(interfaces);
    
//    NSLog(@"手機的IP是:%@", address);
    
    return address;
}


@end


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 定陶县| 赤水市| 买车| 肃南| 德格县| 雷波县| 中牟县| 札达县| 西平县| 德惠市| 盐池县| 沙湾县| 墨竹工卡县| 搜索| 巴楚县| 潼南县| 宝鸡市| 南京市| 万荣县| 南召县| 工布江达县| 郎溪县| 永川市| 房产| 柘城县| 泸溪县| 乌兰县| 塔河县| 蚌埠市| 尉氏县| 红原县| 安康市| 中方县| 交口县| 潼关县| 永泰县| 凤阳县| 灌云县| 鄂托克前旗| 子洲县| 沙坪坝区|