Rewrite IPv4-to-String conversion

Flaky Swift pointer API.
This commit is contained in:
Davide De Rosa 2020-04-11 12:29:40 +02:00
parent af9f7f8165
commit c7595ed295
2 changed files with 28 additions and 12 deletions

View File

@ -110,19 +110,15 @@ public class DNSResolver {
- Returns: The string representation of `ipv4`. - Returns: The string representation of `ipv4`.
*/ */
public static func string(fromIPv4 ipv4: UInt32) -> String { public static func string(fromIPv4 ipv4: UInt32) -> String {
var addr = in_addr(s_addr: CFSwapInt32HostToBig(ipv4)) var remainder = ipv4
var buf = Data(count: Int(INET_ADDRSTRLEN)) var groups: [UInt32] = []
let bufCount = socklen_t(buf.count) var base: UInt32 = 1 << 24
let resultPtr: UnsafePointer<CChar>? = buf.withUnsafeMutableBytes { while base > 0 {
let bufPtr = $0.bindMemory(to: CChar.self).baseAddress! groups.append(remainder / base)
return withUnsafePointer(to: &addr) { remainder %= base
return inet_ntop(AF_INET, $0, bufPtr, bufCount) base >>= 8
}
} }
guard let result = resultPtr else { return groups.map { "\($0)" }.joined(separator: ".")
preconditionFailure()
}
return String(cString: result)
} }
/** /**

View File

@ -106,4 +106,24 @@ class AppExtensionTests: XCTestCase {
} }
waitForExpectations(timeout: 5.0, handler: nil) waitForExpectations(timeout: 5.0, handler: nil)
} }
func testDNSAddressConversion() {
let testStrings = [
"0.0.0.0",
"1.2.3.4",
"111.222.333.444",
"1.0.3.255",
"1.2.255.4",
"1.2.3.0",
"255.255.255.255"
]
for expString in testStrings {
guard let number = DNSResolver.ipv4(fromString: expString) else {
XCTAssertEqual(expString, "111.222.333.444")
continue
}
let string = DNSResolver.string(fromIPv4: number)
XCTAssertEqual(string, expString)
}
}
} }