Return IPv4 network mask for a route

This commit is contained in:
Davide De Rosa 2019-05-01 16:05:50 +02:00
parent 4295e63c98
commit 03a1eb2203
3 changed files with 11 additions and 0 deletions

View File

@ -35,6 +35,7 @@ NS_ASSUME_NONNULL_BEGIN
- (BOOL)isIPv6; - (BOOL)isIPv6;
- (NSString *)network; - (NSString *)network;
- (NSInteger)prefix; - (NSInteger)prefix;
- (nullable NSString *)networkMask; // nil if IPv6
- (nullable NSString *)gateway; - (nullable NSString *)gateway;
- (NSString *)networkInterface; - (NSString *)networkInterface;

View File

@ -176,6 +176,14 @@ static NSString *RoutingTableEntryName(struct sockaddr *sa, struct sockaddr *mas
} }
} }
- (NSString *)networkMask
{
struct in_addr mask;
mask.s_addr = htonl(~((1 << (32 - self.prefix)) - 1));
const char *address = inet_ntoa(mask);
return [NSString stringWithCString:address encoding:NSASCIIStringEncoding];
}
- (BOOL)isDefault - (BOOL)isDefault
{ {
return [self.network isEqualToString:@"default"]; return [self.network isEqualToString:@"default"];

View File

@ -38,6 +38,7 @@ class RoutingTests: XCTestCase {
func testEntryMatch4() { func testEntryMatch4() {
let entry24 = RoutingTableEntry(iPv4Network: "192.168.1.0/24", gateway: nil, networkInterface: "en0") let entry24 = RoutingTableEntry(iPv4Network: "192.168.1.0/24", gateway: nil, networkInterface: "en0")
print(entry24.networkMask()!)
for i in 0x0...0xff { for i in 0x0...0xff {
XCTAssertTrue(entry24.matchesDestination("192.168.1.\(i)")) XCTAssertTrue(entry24.matchesDestination("192.168.1.\(i)"))
} }
@ -46,6 +47,7 @@ class RoutingTests: XCTestCase {
} }
let entry28 = RoutingTableEntry(iPv4Network: "192.168.1.0/28", gateway: nil, networkInterface: "en0") let entry28 = RoutingTableEntry(iPv4Network: "192.168.1.0/28", gateway: nil, networkInterface: "en0")
print(entry28.networkMask()!)
for i in 0x0...0xf { for i in 0x0...0xf {
XCTAssertTrue(entry28.matchesDestination("192.168.1.\(i)")) XCTAssertTrue(entry28.matchesDestination("192.168.1.\(i)"))
} }