Fix IPv4/UInt32 calculations

This commit is contained in:
Davide De Rosa 2018-10-26 18:55:34 +02:00
parent 81a47832c1
commit 9c989dabf5
3 changed files with 11 additions and 7 deletions

View File

@ -15,6 +15,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Use high-level accessories instead of `debugLogKey` and `lastErrorKey`. [#45](https://github.com/keeshux/tunnelkit/pull/45) - Use high-level accessories instead of `debugLogKey` and `lastErrorKey`. [#45](https://github.com/keeshux/tunnelkit/pull/45)
### Fixed
- IPv4/UInt32 calculations were wrong.
## 1.2.2 (2018-10-25) ## 1.2.2 (2018-10-25)
### Changed ### Changed

View File

@ -96,10 +96,10 @@ public class DNSResolver {
} }
public static func string(fromIPv4 ipv4: UInt32) -> String { public static func string(fromIPv4 ipv4: UInt32) -> String {
let a = UInt8(ipv4 & UInt32(0xff)) let a = UInt8((ipv4 >> 24) & UInt32(0xff))
let b = UInt8((ipv4 >> 8) & UInt32(0xff)) let b = UInt8((ipv4 >> 16) & UInt32(0xff))
let c = UInt8((ipv4 >> 16) & UInt32(0xff)) let c = UInt8((ipv4 >> 8) & UInt32(0xff))
let d = UInt8((ipv4 >> 24) & UInt32(0xff)) let d = UInt8(ipv4 & UInt32(0xff))
return "\(a).\(b).\(c).\(d)" return "\(a).\(b).\(c).\(d)"
} }
@ -110,13 +110,13 @@ public class DNSResolver {
return nil return nil
} }
var ipv4: UInt32 = 0 var ipv4: UInt32 = 0
var bits: UInt32 = 0 var bits: UInt32 = 32
comps.forEach { comps.forEach {
guard let octet = UInt32($0), octet <= 255 else { guard let octet = UInt32($0), octet <= 255 else {
return return
} }
bits -= 8
ipv4 |= octet << bits ipv4 |= octet << bits
bits += 8
} }
return ipv4 return ipv4
} }

View File

@ -38,7 +38,7 @@ class DNSTests: XCTestCase {
func testIPv4() { func testIPv4() {
let addr = "1.2.3.4" let addr = "1.2.3.4"
let ip: UInt32 = 0x04030201 let ip: UInt32 = 0x01020304
XCTAssertEqual(DNSResolver.ipv4(fromString: addr), ip) XCTAssertEqual(DNSResolver.ipv4(fromString: addr), ip)
XCTAssertEqual(DNSResolver.string(fromIPv4: ip), addr) XCTAssertEqual(DNSResolver.string(fromIPv4: ip), addr)