IP地址

IP地址分两部分,网络标识和主机标识
网络标识指定子网,主机标识指定子网中某主机

子网掩码

子网掩码用来指明一个IP地址的网络标识和主机标识

网段

在同一网段中,网络标识必须相同
网段的计算由IP地址二进制和子网掩码相与获得

代码

Android

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/** 
* calc the network segment with ip and subnet mask
* @param ip
* @param mask
* @return network segment
*/

public static String CalcNetworkSegment(String ip, String mask) {   
String[] ipList = ip.split("\\u002E");   
String[] maskList = mask.split("\\u002E");   
String[] resultList = new String[ipList.length];   
StringBuilder stringBuilder = new StringBuilder();   
for (int n = 0; n < ipList.length; n++) {       
int ipInt = Integer.parseInt(ipList[n]);       
int maskInt = Integer.parseInt(maskList[n]);       
resultList[n] = String.valueOf(ipInt & maskInt);
stringBuilder.append(resultList[n]);       
if (n != 3)       
stringBuilder.append(".");   
}   
return stringBuilder.toString();
}

iOS (Objc)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (NSString *) calcNetworkSegment:(NSString *) ip mask:(NSString *) mask {
NSArray *ipAddr = [ip componentsSeparatedByString:@"."];
NSArray *maskAddr = [mask componentsSeparatedByString:@"."];
NSMutableString *resultString = [NSMutableString string];

NSInteger arrSize = [ipAddr count];
for (int n =0; n < arrSize-1; n++) {
NSInteger ipInt = [ipAddr[n] integerValue];
NSInteger maskInt = [maskAddr[n] integerValue];
NSInteger resultInt = ipInt & maskInt;
[resultString appendString:[NSString stringWithFormat: @"%d", resultInt]];
if (n != 3) {
[resultString appendString:@"."];
}
}
return resultString;
}