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

View File

@ -106,4 +106,24 @@ class AppExtensionTests: XCTestCase {
}
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)
}
}
}