因項目需求缴淋,手機需與設(shè)備進行socket連接资厉,連接前需判斷手機網(wǎng)絡(luò)和設(shè)備網(wǎng)絡(luò)是否處于同個子網(wǎng)內(nèi)。網(wǎng)絡(luò)搜索無果后罢吃,自己根據(jù)邏輯寫了個粗糙的判斷方法楚午,希望能幫助到有需要的人。首篇文章尿招,如有錯誤矾柜,歡迎指正。Thanks?(?ω?)?
獲取手機當(dāng)前IP地址
#pragma mark - 獲取IP地址
+(NSString *)getIPAddress {
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// 檢索當(dāng)前接口,在成功時,返回0
success = getifaddrs(&interfaces);
if (success == 0) {
// 循環(huán)鏈表的接口
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// 檢查接口是否en0 wifi連接在iPhone上
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// 得到NSString從C字符串
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// 釋放內(nèi)存
freeifaddrs(interfaces);
return address;
}
獲取子網(wǎng)掩碼
#pragma mark - 獲取子網(wǎng)掩碼
+ (NSString*)getCurrentWifiMessage {
NSString *address = nil;
NSString *subNetMask = nil;
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"]) {
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)];
subNetMask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return subNetMask;
}
十進制轉(zhuǎn)二進制
#pragma mark - 十進制轉(zhuǎn)二進制
+ (NSString *)getBinaryByHex:(NSInteger)decimal {
NSString *binary = @"";
while (decimal) {
binary = [[NSString stringWithFormat:@"%ld", decimal % 2] stringByAppendingString:binary];
if (decimal / 2 < 1) {
break;
}
decimal = decimal / 2 ;
}
if (binary.length % 4 != 0) {
NSMutableString *mStr = [[NSMutableString alloc]init];;
for (int i = 0; i < 4 - binary.length % 4; i++) {
[mStr appendString:@"0"];
}
binary = [mStr stringByAppendingString:binary];
}
return binary;
}
獲取某個字符在字符串中的所有位置數(shù)組
#pragma mark - 獲取某個字符在字符串中的所有位置數(shù)組
+ (NSMutableArray *)getRangeStr:(NSString *)text findText:(NSString *)findText {
NSMutableArray *arrayRanges = [NSMutableArray arrayWithCapacity:3];
if (findText == nil && [findText isEqualToString:@""]) {
return nil;
}
NSRange rang = [text rangeOfString:findText]; //獲取第一次出現(xiàn)的range
if (rang.location != NSNotFound && rang.length != 0) {
[arrayRanges addObject:[NSNumber numberWithInteger:rang.location]];//將第一次的加入到數(shù)組中
NSRange rang1 = {0,0};
NSInteger location = 0;
NSInteger length = 0;
for (int i = 0;; i++) {
if (0 == i) {
//去掉這個abc字符串
location = rang.location + rang.length;
length = text.length - rang.location - rang.length;
rang1 = NSMakeRange(location, length);
} else {
location = rang1.location + rang1.length;
length = text.length - rang1.location - rang1.length;
rang1 = NSMakeRange(location, length);
}
//在一個range范圍內(nèi)查找另一個字符串的range
rang1 = [text rangeOfString:findText options:NSCaseInsensitiveSearch range:rang1];
if (rang1.location == NSNotFound && rang1.length == 0) {
break;
} else//添加符合條件的location進數(shù)組
[arrayRanges addObject:[NSNumber numberWithInteger:rang1.location]];
}
return arrayRanges;
}
return nil;
}
獲取IP或者子網(wǎng)掩碼每段的二進制字符串
#pragma mark - 獲取IP和子網(wǎng)掩碼每段的二進制
+ (NSArray *)fetchBinaryListWithStr:(NSString *)string {
NSArray *maskPositionList = [self getRangeStr:string findText:@"."];
NSMutableArray *maskList = [[NSMutableArray alloc] init];
for (int i = 0; i < [maskPositionList count]; i++) {
NSString *str;
if (i == 0) {
str = [self getBinaryByHex:[[string substringWithRange:NSMakeRange(0, [[maskPositionList objectAtIndex:i] integerValue])] integerValue]];
} else {
str = [self getBinaryByHex:[[string substringWithRange:NSMakeRange([[maskPositionList objectAtIndex:i-1] integerValue] + 1, [[maskPositionList objectAtIndex:i] integerValue] - [[maskPositionList objectAtIndex:i-1] integerValue] - 1)] integerValue]];
}
for (int i = (int)str.length; i < 12; i++) {
str = [NSString stringWithFormat:@"0%@",str];
}
[maskList addObject:str];
}
NSString *lastStr = [self getBinaryByHex:[[string substringWithRange:NSMakeRange([[maskPositionList objectAtIndex:[maskPositionList count] - 1] integerValue] + 1, string.length - [[maskPositionList objectAtIndex:[maskPositionList count] - 1] integerValue] - 1)] integerValue]];
for (int i = (int)lastStr.length; i < 12; i++) {
lastStr = [NSString stringWithFormat:@"0%@",lastStr];
}
[maskList addObject:lastStr];
return maskList;
}
二進制的&運算
#pragma mark - 二進制與運算
+ (NSString *)andOperationWithFirst:(NSString *)first andSecond:(NSString *)second {
NSString *resultStr = nil;
for (int i = 0; i < first.length; i++) {
if (i == 0) {
if ([[first substringWithRange:NSMakeRange(0, 1)] integerValue] == 1 && [[second substringWithRange:NSMakeRange(0, 1)] integerValue] == 1) {
resultStr = [NSString stringWithFormat:@"1"];
} else {
resultStr = [NSString stringWithFormat:@"0"];
}
} else {
if ([[first substringWithRange:NSMakeRange(i, 1)] integerValue] == 1 && [[second substringWithRange:NSMakeRange(i, 1)] integerValue] == 1) {
resultStr = [NSString stringWithFormat:@"%@1",resultStr];
} else {
resultStr = [NSString stringWithFormat:@"%@0",resultStr];
}
}
}
return resultStr;
}
二進制轉(zhuǎn)十進制
+ (NSString *)getDecimalByBinary:(NSString *)binary {
NSInteger decimal = 0;
for (int i = 0; i < binary.length; i++) {
NSString *number = [binary substringWithRange:NSMakeRange(binary.length - i - 1, 1)];
if ([number isEqualToString:@"1"]) {
decimal += pow(2, i);
}
}
return [NSString stringWithFormat:@"%ld",(long)decimal];
}
判斷IP是否在同個子網(wǎng)內(nèi)
+ (BOOL)whetherTheSameSubNetWithDeviceIpStr:(NSString *)deviceIp {
BOOL result = NO;
//子網(wǎng)掩碼
NSString *mask = [UtilsMacro getCurrentWifiMessage];
NSArray *maskList = [UtilsMacro fetchBinaryListWithStr:mask];
//手機IP地址
NSString *currentIP = [UtilsMacro getIPAddress];
NSArray *ipList = [UtilsMacro fetchBinaryListWithStr:currentIP];
NSArray *deviceList = [UtilsMacro fetchBinaryListWithStr:deviceIp];
NSMutableArray *deviceAndResult = [[NSMutableArray alloc] init];
NSMutableArray *phoneAndResult = [[NSMutableArray alloc] init];
for (int i = 0; i < [maskList count]; i++) {
[deviceAndResult addObject:[UtilsMacro getDecimalByBinary:[UtilsMacro andOperationWithFirst:[maskList objectAtIndex:i] andSecond:[deviceList objectAtIndex:i]]]];
[phoneAndResult addObject:[UtilsMacro getDecimalByBinary:[UtilsMacro andOperationWithFirst:[maskList objectAtIndex:i] andSecond:[ipList objectAtIndex:i]]]];
}
NSString *deviceResult = [deviceAndResult componentsJoinedByString:@"."];
NSLog(@"deviceResult:%@",deviceResult);
NSString *phoneResult = [phoneAndResult componentsJoinedByString:@"."];
NSLog(@"phoneResult:%@",phoneResult);
if ([deviceResult isEqualToString:phoneResult]) {
result = YES;
} else {
result = NO;
}
return result;
}