更新EsptouchForIOS

This commit is contained in:
kai60
2020-06-10 20:27:25 +08:00
parent 1f69653c19
commit b8d6ad08ea
42 changed files with 1625 additions and 853 deletions
+19
View File
@@ -0,0 +1,19 @@
//
// ESPAES.h
// EspTouchDemo
//
// Created by AE on 2018/4/5.
//
#import <Foundation/Foundation.h>
@interface ESPAES : NSObject {
@private NSString *key;
}
- (instancetype)initWithKey:(NSString *)secretKey;
- (NSData *)AES128EncryptData:(NSData *)data;
- (NSData *)AES128DecryptData:(NSData *)data;
@end
+66
View File
@@ -0,0 +1,66 @@
//
// ESPAES.m
// EspTouchDemo
//
// Created by AE on 2018/4/5.
//
#import "ESPAES.h"
#import <CommonCrypto/CommonCryptor.h>
@implementation ESPAES
- (instancetype)initWithKey:(NSString *)secretKey
{
self = [super init];
if (self) {
key = secretKey;
}
return self;
}
- (NSData *)AES128EncryptData:(NSData *)data {
char keyPtr[kCCKeySizeAES128+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr, kCCBlockSizeAES128,
NULL,
[data bytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
- (NSData *)AES128DecryptData:(NSData *)data {
char keyPtr[kCCKeySizeAES128+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr, kCCBlockSizeAES128,
NULL,
[data bytes], dataLength,
buffer, bufferSize,
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer);
return nil;
}
@end
+22
View File
@@ -0,0 +1,22 @@
//
// EspNetUtils.h
// Esp32Mesh
//
// Created by AE on 2018/4/19.
// Copyright © 2018年 AE. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface ESPTools : NSObject
+ (nullable NSString *)getCurrentWiFiSsid;
+ (nullable NSString *)getCurrentBSSID;
+ (NSString *)getIPAddress:(BOOL)preferIPv4;
+ (NSDictionary *)getIPAddresses;
NS_ASSUME_NONNULL_END
@end
+132
View File
@@ -0,0 +1,132 @@
//
// EspNetUtils.m
// Esp32Mesh
//
// Created by AE on 2018/4/19.
// Copyright © 2018年 AE. All rights reserved.
//
#import "ESPTools.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <net/if.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#define IOS_CELLULAR @"pdp_ip0"
#define IOS_WIFI @"en0"
#define IOS_VPN @"utun0"
#define IP_ADDR_IPv4 @"ipv4"
#define IP_ADDR_IPv6 @"ipv6"
@implementation ESPTools
+ (nullable NSString *)getCurrentWiFiSsid {
NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
id info = nil;
for (NSString *ifnam in ifs) {
info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
if (info && [info count]) {
break;
}
}
// Key: BSSID, SSID, SSIDDATA
return [(NSDictionary*)info objectForKey:@"SSID"];
}
+ (nullable NSString *)getCurrentBSSID {
NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
id info = nil;
for (NSString *ifnam in ifs) {
info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
if (info && [info count]) {
break;
}
}
// Key: BSSID, SSID, SSIDDATA
return [(NSDictionary*)info objectForKey:@"BSSID"];
}
+ (NSString *)getIPAddress:(BOOL)preferIPv4 {
NSArray *searchArray = preferIPv4 ?
@[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
@[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
NSDictionary *addresses = [self getIPAddresses];
NSLog(@"addresses: %@", addresses);
__block NSString *address;
[searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) {
address = addresses[key];
//筛选出IP地址格式
if([self isValidatIP:address]) *stop = YES;
} ];
return address ? address : @"0.0.0.0";
}
+ (BOOL)isValidatIP:(NSString *)ipAddress {
if (ipAddress.length == 0) {
return NO;
}
NSString *urlRegEx = @"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];
if (regex != nil) {
NSTextCheckingResult *firstMatch=[regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];
if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:0];
NSString *result=[ipAddress substringWithRange:resultRange];
//输出结果
NSLog(@"ESPTools 输出结果:%@",result);
return YES;
}
}
return NO;
}
+ (NSDictionary *)getIPAddresses {
NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
// retrieve the current interfaces - returns 0 on success
struct ifaddrs *interfaces;
if(!getifaddrs(&interfaces)) {
// Loop through linked list of interfaces
struct ifaddrs *interface;
for(interface=interfaces; interface; interface=interface->ifa_next) {
if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
continue; // deeply nested code harder to read
}
const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
NSString *type;
if(addr->sin_family == AF_INET) {
if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
type = IP_ADDR_IPv4;
}
} else {
const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
type = IP_ADDR_IPv6;
}
}
if(type) {
NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
addresses[key] = [NSString stringWithUTF8String:addrBuf];
}
}
}
// Free memory
freeifaddrs(interfaces);
}
return [addresses count] ? addresses : nil;
}
@end
+20
View File
@@ -0,0 +1,20 @@
//
// ESPVersionMacro.h
// suite
//
// Created by fby on 5/16/16.
// Copyright © 2016 fby. All rights reserved.
//
#ifndef ESPVersionMacro_h
#define ESPVersionMacro_h
#import <UIKit/UIKit.h>
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
#endif /* ESPVersionMacro_h */
+128
View File
@@ -0,0 +1,128 @@
//
// ESP_ByteUtil.h
// EspTouchDemo
//
// Created by fby on 4/7/15.
// Copyright (c) 2015 fby. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ESP_ByteUtil : NSObject
#define ESPTOUCH_NSStringEncoding NSUTF8StringEncoding
/**
* Convert uint8 into char( we treat char as uint8)
*
* @param uint8
* the unit8 to be converted
* @return the byte of the unint8
*/
+ (Byte) convertUint8toByte:(char) uint8;
/**
* Convert char into uint8( we treat char as uint8 )
*
* @param b
* the byte to be converted
* @return the UInt8(uint8)
*/
+ (UInt8) convertByte2Uint8:(Byte) b;
/**
* Convert byte to Hex String
*
* @param b
* the byte to be converted
* @return the Hex String
*/
+ (NSString *) convertByte2HexString:(Byte) b;
/**
* Split uint8 to 2 bytes of high byte and low byte. e.g. 20 = 0x14 should
* be split to [0x01,0x04] 0x01 is high byte and 0x04 is low byte
*
* @param uint8
* the char(uint8)
* @return the high and low bytes be split, byte[0] is high and byte[1] is
* low
*/
+ (NSData *) splitUint8To2Bytes: (UInt8) uint8;
/**
* Combine 2 bytes (high byte and low byte) to one whole byte
*
* @param high
* the high byte
* @param low
* the low byte
* @return the whole byte
*/
+ (Byte) combine2bytesToOneWithHigh: (Byte) high andLow: (Byte) low;
/**
* Combine 2 bytes (high byte and low byte) to one UInt16
*
* @param high
* the high byte
* @param low
* the low byte
* @return the UInt8
*/
+ (UInt16) combine2bytesToU16WithHigh: (Byte) high andLow: (Byte) low;
/**
* Generate the random byte to be sent
*
* @return the random byte
*/
+ (Byte) randomByte;
/**
* Generate the random byte to be sent
*
* @param len
* the len presented by u8
* @return the byte[] to be sent
*/
+ (NSData *) randomBytes: (UInt8) len;
+ (NSData *) genSpecBytesWithU16: (UInt16) len;
/**
* Generate the specific byte to be sent
* @param len
* the len presented by byte
* @return the byte[]
*/
+ (NSData *) genSpecBytesWithU8:(Byte) len;
+ (NSString *) parseBssid:(Byte[]) bssidBytes Offset: (int) offset Count: (int) count;
/**
* parse "24,-2,52,-102,-93,-60" to "18,fe,34,9a,a3,c4" parse the bssid from
* hex to String
*
* @param bssidBytes
* the hex bytes bssid, e.g. {24,-2,52,-102,-93,-60}
* @param len
* the len of bssidBytes
* @return the String of bssid, e.g. 18fe349aa3c4
*/
+ (NSString *) parseBssid:(Byte[]) bssidBytes Len: (int) len;
/**
* @param string the string to be used
* @return the Byte[] of string according to ESPTOUCH_NSStringEncoding
*/
+ (NSData *) getBytesByNSString: (NSString *)string;
/**
* get hex string transformed by data
* @param data the data to be transformed
* @return the hex String transformed by data
*/
+ (NSString *) getHexStringByData: (NSData *)data;
@end
+159
View File
@@ -0,0 +1,159 @@
//
// ESP_ByteUtil.m
// EspTouchDemo
//
// Created by fby on 4/7/15.
// Copyright (c) 2015 fby. All rights reserved.
//
#import "ESP_ByteUtil.h"
@implementation ESP_ByteUtil
+ (Byte) convertUint8toByte:(char) uint8
{
return (Byte)uint8;
}
+ (UInt8) convertByte2Uint8:(Byte) b
{
return (UInt8) (b & 0xff);
}
+ (NSString *) convertByte2HexString:(Byte) b
{
UInt8 u8 = [self convertByte2Uint8:b];
return [NSString stringWithFormat:@"%x",u8];
}
+ (unsigned int)intFromHexString:(NSString *) hexStr
{
unsigned int hexInt = 0;
// Create scanner
NSScanner *scanner = [NSScanner scannerWithString:hexStr];
// Tell scanner to skip the # character
// [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];
// Scan hex value
[scanner scanHexInt:&hexInt];
return hexInt;
}
+ (NSData *) splitUint8To2Bytes: (UInt8) uint8
{
NSString *hexString = [NSString stringWithFormat:@"%x",uint8];
Byte low;
Byte high;
if (hexString.length > 1)
{
high = [self intFromHexString:[hexString substringWithRange:NSMakeRange(0, 1)]];
low =[self intFromHexString:[hexString substringWithRange:NSMakeRange(1, 1)]];
}
else
{
high = 0;
low = [self intFromHexString:[hexString substringWithRange:NSMakeRange(0, 1)]];
}
Byte bytes[] = { high, low };
NSData *data = [[NSData alloc] initWithBytes:bytes length:2];
return data;
}
+ (Byte) combine2bytesToOneWithHigh: (Byte) high andLow: (Byte) low
{
return (Byte) (high << 4 | low);
}
+ (UInt16) combine2bytesToU16WithHigh: (Byte) high andLow: (Byte) low
{
UInt8 highU8 = [self convertByte2Uint8:high];
UInt8 lowU8 = [self convertByte2Uint8:low];
return (highU8 << 8 | lowU8);
}
+ (Byte) randomByte
{
return arc4random() % 256;
}
+ (NSData *) randomBytes: (UInt8) len
{
Byte bytes[len];
for (int i = 0; i < len; i++) {
bytes[i] = [self randomByte];
}
NSData *data = [[NSData alloc]initWithBytes:bytes length:len];
return data;
}
+ (NSData *) genSpecBytesWithU16:(UInt16)len
{
Byte bytes[len];
for (int i = 0; i < len; i++) {
bytes[i] = '1';
}
NSData *data = [[NSData alloc]initWithBytes:bytes length:len];
return data;
}
+ (NSData *) genSpecBytesWithU8:(Byte) len
{
UInt8 u8 = [self convertByte2Uint8:len];
return [self genSpecBytesWithU16:u8];
}
+ (NSString *) parseBssid:(Byte[]) bssidBytes Offset: (int) offset Count: (int) count
{
Byte bytes[count];
for (int i = 0; i < count; i++ )
{
bytes[i] = bssidBytes[i + offset];
}
return [self parseBssid:bytes Len:count];
}
+ (NSString *) parseBssid:(Byte[]) bssidBytes Len:(int)len
{
NSMutableString *mStr = [[NSMutableString alloc]init];
int k;
NSString* hexK;
NSString* str;
for (int i = 0; i < len; i++)
{
k = 0xff & bssidBytes[i];
hexK = [NSString stringWithFormat:@"%x", k];
str = ((k < 16) ? ([NSString stringWithFormat:@"0%@",hexK ]) : (hexK));
[mStr appendString:str];
}
return mStr;
}
+ (NSData *) getBytesByNSString: (NSString *)string
{
NSUInteger numberOfBytes = [string lengthOfBytesUsingEncoding:ESPTOUCH_NSStringEncoding];
Byte bytes[numberOfBytes];
NSRange range = NSMakeRange(0, numberOfBytes);
[string getBytes:bytes maxLength:numberOfBytes usedLength:nil encoding:ESPTOUCH_NSStringEncoding options:0 range:range remainingRange:NULL];
NSData *data = [[NSData alloc]initWithBytes:bytes length:numberOfBytes];
return data;
}
+ (NSString *) getHexStringByData:(NSData *)data
{
NSMutableString* mStr = [[NSMutableString alloc]init];
NSUInteger totalLen = [data length];
Byte bytes[totalLen];
[data getBytes:&bytes length:totalLen];
for (int i = 0; i < totalLen; i++)
{
NSString *hexString = [[NSString alloc]initWithFormat:@"0x%.2x ",bytes[i]];
[mStr appendString:hexString];
}
return mStr;
}
@end
+61
View File
@@ -0,0 +1,61 @@
//
// ESP_CRC8.h
// EspTouchDemo
//
// Created by fby on 3/23/15.
// Copyright (c) 2015 fby. All rights reserved.
//
#import <Foundation/Foundation.h>
#define CRC_POLYNOM 0x8c
#define CRC_INITIAL 0x00
// the interface is copied from the interface Checksum from Java
@interface ESP_CRC8 : NSObject
/**
* Returns the current calculated checksum value.
*
* @return the checksum.
*/
- (long)getValue;
/**
* Resets the checksum value applied before beginning calculations on a new
* stream of data.
*/
- (void)reset;
/**
* Updates the checksum with the given bytes.
*
* @param buf
* the byte array from which to read the bytes.
* @param off
* the initial position in {@code buf} to read the bytes from.
* @param nbytes
* the number of bytes to read from {@code buf}.
*/
- (void)updateWithBuf:(Byte[])buf Off:(int)off Nbytes:(int)nbytes;
/**
* Updates the checksum with the given bytes.
*
* @param buf
* the byte array from which to read the bytes.
* @param nbytes
* the number of bytes to read from {@code buf}.
*/
- (void)updateWithBuf:(Byte [])buf Nbytes:(int)nbytes;
/**
* Updates the checksum value with the given byte.
*
* @param value
* the byte to update the checksum with.
*/
- (void)updateWithValue:(int)value;
@end
+80
View File
@@ -0,0 +1,80 @@
//
// ESP_CRC8.m
// EspTouchDemo
//
// Created by fby on 3/23/15.
// Copyright (c) 2015 fby. All rights reserved.
//
#import "ESP_CRC8.h"
@implementation ESP_CRC8
static ushort crcTable[256];
NSNumber *_init;
NSNumber *_value;
+(void) initialize
{
for (ushort dividend=0; dividend < 256; dividend++)
{
ushort remainder = dividend;
for (ushort bit = 0; bit < 8; ++bit)
{
if ((remainder & 0x01) != 0)
{
remainder = (remainder >> 1) ^ CRC_POLYNOM;
}
else
{
remainder >>= 1;
}
crcTable[dividend] = (ushort) remainder;
}
}
}
-(id) init
{
if(self = [super init])
{
_init = [[NSNumber alloc]initWithInt:CRC_INITIAL];
_value = [[NSNumber alloc] initWithInt:CRC_INITIAL];
}
return self;
}
- (long)getValue
{
return [_value unsignedShortValue] & 0xff;
}
- (void)reset
{
_value = _init;
}
- (void)updateWithBuf:(Byte[])buf Off:(int)off Nbytes:(int)nbytes
{
for (int i = 0; i < nbytes; i++)
{
int data = buf[off + i] ^ _value.intValue;
int value = crcTable[data & 0xff] ^ (_value.intValue << 8);
_value = [NSNumber numberWithInt:value];
}
}
- (void)updateWithBuf:(Byte [])buf Nbytes:(int)nbytes
{
[self updateWithBuf:buf Off:0 Nbytes:nbytes];
}
- (void)updateWithValue:(int)value
{
Byte b[1] = { (Byte)value };
[self updateWithBuf:b Nbytes:1];
}
@end
+82
View File
@@ -0,0 +1,82 @@
//
// ESPNetUtil.h
// EspTouchDemo
//
// Created by fby on 5/15/15.
// Copyright (c) 2015 fby. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ESP_NetUtil : NSObject
/**
* get local ip v4 or nil
*
* @return local ip v4 or nil
*/
+ (NSString *) getLocalIPv4;
/**
* get local ip v6 or nil
*
* @return local ip v6 or nil
*/
+ (NSString *) getLocalIPv6;
/**
* whether the ipAddr is v4
*
* @return whether the ipAddr is v4
*/
+ (BOOL) isIPv4Addr:(NSString *)ipAddr;
/**
* whether the ipAddr v4 is private
*
* @return whether the ipAddr v4 is private
*/
+ (BOOL) isIPv4PrivateAddr:(NSString *)ipAddr;
/**
* get the local ip address by local inetAddress ip4
*
* @param localInetAddr4 local inetAddress ip4
*/
+ (NSData *) getLocalInetAddress4ByAddr:(NSString *) localInetAddr4;
/**
* get the invented local ip address by local port
*
*/
+ (NSData *) getLocalInetAddress6ByPort:(int) localPort;
/**
* parse InetAddress
*/
+ (NSData *) parseInetAddrByData: (NSData *) inetAddrData andOffset: (int) offset andCount: (int) count;
/**
* descrpion inetAddrData for print pretty IPv4
*/
+ (NSString *) descriptionInetAddr4ByData: (NSData *) inetAddrData;
/**
* descrpion inetAddrData for print pretty IPv6
*/
+ (NSString *) descriptionInetAddr6ByData: (NSData *) inetAddrData;
/**
* parse bssid
*
* @param bssid the bssid
* @return byte converted from bssid
*/
+ (NSData *) parseBssid2bytes: (NSString *) bssid;
/**
* send a dummy GET to "https://8.8.8.8" just to get Network Permission after ios10.0(including)
*/
+ (void) tryOpenNetworkPermission;
@end
+153
View File
@@ -0,0 +1,153 @@
//
// ESPNetUtil.m
// EspTouchDemo
//
// Created by fby on 5/15/15.
// Copyright (c) 2015 fby. All rights reserved.
//
#import "ESP_NetUtil.h"
#import "ESP_WifiUtil.h"
#import "ESP_ByteUtil.h"
#import "ESPVersionMacro.h"
#define IP4_LEN 4
#define IP6_LEN 16
@implementation ESP_NetUtil
/**
* get local ip v4 or nil
*
* @return local ip v4 or nil
*/
+ (NSString *) getLocalIPv4
{
return [ESP_WifiUtil getIPAddress4];
}
/**
* get local ip v6 or nil
*
* @return local ip v6 or nil
*/
+ (NSString *) getLocalIPv6
{
return [ESP_WifiUtil getIpAddress6];
}
+ (BOOL) isIPv4Addr:(NSString *)ipAddr
{
NSArray *ip4array = [ipAddr componentsSeparatedByString:@"."];
return [ip4array count]==4;
}
+ (BOOL) isIPv4PrivateAddr:(NSString *)ipAddr4
{
NSArray *ip4array = [ipAddr4 componentsSeparatedByString:@"."];
Byte byte0 = [[ip4array objectAtIndex:0]intValue];
Byte byte1 = [[ip4array objectAtIndex:1]intValue];
// Byte byte2 = [[ip4array objectAtIndex:2]intValue];
// Byte byte3 = [[ip4array objectAtIndex:3]intValue];
if (byte0==10) {
// 10.0.0.0~10.255.255.255
return YES;
} else if (byte0==172&&16<=byte1&&byte1<=31) {
// 172.16.0.0~172.31.255.255
return YES;
} else if (byte0==192&&byte1==168) {
// 192.168.0.0~192.168.255.255
return YES;
}
return NO;
}
+ (NSData *) getLocalInetAddress4ByAddr:(NSString *) localInetAddr4
{
NSArray *ip4array = [localInetAddr4 componentsSeparatedByString:@"."];
Byte byte0 = [[ip4array objectAtIndex:0]intValue];
Byte byte1 = [[ip4array objectAtIndex:1]intValue];
Byte byte2 = [[ip4array objectAtIndex:2]intValue];
Byte byte3 = [[ip4array objectAtIndex:3]intValue];
Byte bytes[] = {byte0,byte1,byte2,byte3};
NSData *ip4data = [NSData dataWithBytes:bytes length:IP4_LEN];
return ip4data;
}
+ (NSData *) getLocalInetAddress6ByPort:(int) localPort
{
Byte lowPort = localPort & 0xff;
Byte highPort = (localPort>>8) & 0xff;
Byte bytes[] = {highPort,lowPort,0xff,0xff};
NSData *ip6data = [NSData dataWithBytes:bytes length:IP4_LEN];
return ip6data;
}
+ (NSData *) parseInetAddrByData: (NSData *) inetAddrData andOffset: (int) offset andCount: (int) count
{
return [inetAddrData subdataWithRange:NSMakeRange(offset, count)];
}
+ (NSString *) descriptionInetAddr4ByData: (NSData *) inetAddrData
{
// check whether inetAddrData is belong to IPv4
if ([inetAddrData length]!=IP4_LEN) {
return nil;
}
Byte inetAddrBytes[IP4_LEN];
[inetAddrData getBytes:inetAddrBytes length:IP4_LEN];
// hard coding
return [NSString stringWithFormat:@"%d.%d.%d.%d",inetAddrBytes[0],inetAddrBytes[1],inetAddrBytes[2],inetAddrBytes[3]];
}
+ (NSString *) descriptionInetAddr6ByData: (NSData *) inetAddrData
{
// check whether inetAddrData is belong to IPv4
if ([inetAddrData length]!=IP6_LEN) {
return nil;
}
Byte inetAddrBytes[IP6_LEN];
[inetAddrData getBytes:inetAddrBytes length:IP6_LEN];
// hard coding
return [NSString stringWithFormat:@"%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",inetAddrBytes[0],inetAddrBytes[1],inetAddrBytes[2],inetAddrBytes[3],inetAddrBytes[4],inetAddrBytes[5],inetAddrBytes[6],inetAddrBytes[7],inetAddrBytes[8],inetAddrBytes[9],inetAddrBytes[10],inetAddrBytes[11],inetAddrBytes[12],inetAddrBytes[13],inetAddrBytes[14],inetAddrBytes[15]];
}
+ (NSData *) parseBssid2bytes: (NSString *) bssid
{
NSArray *bssidArray = [bssid componentsSeparatedByString:@":"];
NSInteger size = [bssidArray count];
Byte bssidBytes[size];
for (NSInteger i = 0; i < size; i++) {
NSString *bssidStr = [bssidArray objectAtIndex:i];
bssidBytes[i] = strtoul([bssidStr UTF8String], 0, 16);
}
return [[NSData alloc]initWithBytes:bssidBytes length:size];
}
+ (NSURLSessionConfiguration *) DEFAULT_SESSION_CONFIGURATION
{
static dispatch_once_t predicate;
static NSURLSessionConfiguration *DEFAULT_SESSION_CONFIGURATION;
dispatch_once(&predicate, ^{
DEFAULT_SESSION_CONFIGURATION = [NSURLSessionConfiguration defaultSessionConfiguration];
});
return DEFAULT_SESSION_CONFIGURATION;
}
+ (void) tryOpenNetworkPermission
{
// only ios 10.0 later required to try open network permission
if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
NSURL *url = [NSURL URLWithString:@"https://8.8.8.8"];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:1000];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:[self DEFAULT_SESSION_CONFIGURATION] delegate:nil delegateQueue:[NSOperationQueue currentQueue]];
[[urlSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
}] resume];
}
}
@end
+33
View File
@@ -0,0 +1,33 @@
//
// ESP_WifiUtil.h
// EspTouchDemo
//
// Created by fby on 6/15/16.
// Copyright © 2016 fby. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface ESP_WifiUtil : NSObject
// refer to http://stackoverflow.com/questions/7072989/iphone-ipad-osx-how-to-get-my-ip-address-programmatically
+ (NSString *)getIPAddress:(BOOL)preferIPv4;
// refer to http://stackoverflow.com/questions/7072989/iphone-ipad-osx-how-to-get-my-ip-address-programmatically
+ (NSDictionary *)getIPAddresses;
/**
* get local ip address by IPv4
*
* @return local ip address by IPv4(or nil when en0/ipv4 unaccessible)
*/
+ (NSString *)getIPAddress4;
/**
* get local ip address by IPv6
*
* @return local ip address by IPv6(or nil when en0/ipv6 unaccessible)
*/
+ (NSString *)getIpAddress6;
@end
+95
View File
@@ -0,0 +1,95 @@
//
// ESP_WifiUtil.m
// EspTouchDemo
//
// Created by fby on 6/15/16.
// Copyright © 2016 fby. All rights reserved.
//
#import "ESP_WifiUtil.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
#define IOS_CELLULAR @"pdp_ip0"
#define IOS_WIFI @"en0"
#define IOS_VPN @"utun0"
#define IP_ADDR_IPv4 @"ipv4"
#define IP_ADDR_IPv6 @"ipv6"
@implementation ESP_WifiUtil
+ (NSString *)getIPAddress:(BOOL)preferIPv4
{
NSArray *searchArray = preferIPv4 ?
@[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
@[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
NSDictionary *addresses = [self getIPAddresses];
// NSLog(@"addresses: %@", addresses);
__block NSString *address;
[searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
{
address = addresses[key];
if(address) *stop = YES;
} ];
return address ? address : @"0.0.0.0";
}
+ (NSDictionary *)getIPAddresses
{
NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
// retrieve the current interfaces - returns 0 on success
struct ifaddrs *interfaces;
if(!getifaddrs(&interfaces)) {
// Loop through linked list of interfaces
struct ifaddrs *interface;
for(interface=interfaces; interface; interface=interface->ifa_next) {
if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
continue; // deeply nested code harder to read
}
const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
NSString *type;
if(addr->sin_family == AF_INET) {
if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
type = IP_ADDR_IPv4;
}
} else {
const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
type = IP_ADDR_IPv6;
}
}
if(type) {
NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
addresses[key] = [NSString stringWithUTF8String:addrBuf];
}
}
}
// Free memory
freeifaddrs(interfaces);
}
return [addresses count] ? addresses : nil;
}
+ (NSString *)getIPAddress4
{
NSString *key = [NSString stringWithFormat:@"%@/%@",IOS_WIFI,IP_ADDR_IPv4];
NSString *ipv4 = [[self getIPAddresses]objectForKey:key];
return ipv4;
}
+ (NSString *)getIpAddress6
{
NSString *key = [NSString stringWithFormat:@"%@/%@",IOS_WIFI,IP_ADDR_IPv6];
NSString *ipv6 = [[self getIPAddresses]objectForKey:key];
return ipv6;
}
@end