因项目需求,手机需与设备进行socket连接,连接前需判断手机网络和设备网络是否处于同个子网内。网络搜索无果后,自己根据逻辑写了个粗糙的判断方法,希望能帮助到有需要的人。首篇文章,如有错误,欢迎指正。Thanks♪(・ω・)ノ
获取手机当前IP地址
#pragma mark - 获取IP地址
+(NSString *)getIPAddress {
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// 检索当前接口,在成功时,返回0
success = getifaddrs(&interfaces);
if (success == 0) {
// 循环链表的接口
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;
}
}
// 释放内存
freeifaddrs(interfaces);
return address;
}
获取子网掩码
#pragma mark - 获取子网掩码
+ (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;
}
十进制转二进制
#pragma mark - 十进制转二进制
+ (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;
}
获取某个字符在字符串中的所有位置数组
#pragma mark - 获取某个字符在字符串中的所有位置数组
+ (NSMutableArray *)getRangeStr:(NSString *)text findText:(NSString *)findText {
NSMutableArray *arrayRanges = [NSMutableArray arrayWithCapacity:3];
if (findText == nil && [findText isEqualToString:@""]) {
return nil;
}
NSRange rang = [text rangeOfString:findText]; //获取第一次出现的range
if (rang.location != NSNotFound && rang.length != 0) {
[arrayRanges addObject:[NSNumber numberWithInteger:rang.location]];//将第一次的加入到数组中
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范围内查找另一个字符串的range
rang1 = [text rangeOfString:findText options:NSCaseInsensitiveSearch range:rang1];
if (rang1.location == NSNotFound && rang1.length == 0) {
break;
} else//添加符合条件的location进数组
[arrayRanges addObject:[NSNumber numberWithInteger:rang1.location]];
}
return arrayRanges;
}
return nil;
}
获取IP或者子网掩码每段的二进制字符串
#pragma mark - 获取IP和子网掩码每段的二进制
+ (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;
}
二进制转十进制
+ (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是否在同个子网内
+ (BOOL)whetherTheSameSubNetWithDeviceIpStr:(NSString *)deviceIp {
BOOL result = NO;
//子网掩码
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;
}