From e198e80595a6f4a8421894e4d22c16090069912c Mon Sep 17 00:00:00 2001 From: Davide De Rosa Date: Mon, 5 Nov 2018 19:24:39 +0100 Subject: [PATCH 1/2] Use standard inet_ntop/pton for IPv4 conversion Swap endianness internally. --- .../Sources/AppExtension/DNSResolver.swift | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/TunnelKit/Sources/AppExtension/DNSResolver.swift b/TunnelKit/Sources/AppExtension/DNSResolver.swift index 4276daf..adc96bc 100644 --- a/TunnelKit/Sources/AppExtension/DNSResolver.swift +++ b/TunnelKit/Sources/AppExtension/DNSResolver.swift @@ -96,29 +96,29 @@ public class DNSResolver { } public static func string(fromIPv4 ipv4: UInt32) -> String { - let a = UInt8((ipv4 >> 24) & UInt32(0xff)) - let b = UInt8((ipv4 >> 16) & UInt32(0xff)) - let c = UInt8((ipv4 >> 8) & UInt32(0xff)) - let d = UInt8(ipv4 & UInt32(0xff)) - - return "\(a).\(b).\(c).\(d)" + var addr = in_addr(s_addr: CFSwapInt32HostToBig(ipv4)) + var buf = Data(count: Int(INET_ADDRSTRLEN)) + let bufCount = socklen_t(buf.count) + let resultPtr = buf.withUnsafeMutableBytes { (bufPtr) in + return withUnsafePointer(to: &addr) { + return inet_ntop(AF_INET, $0, bufPtr, bufCount) + } + } + guard let result = resultPtr else { + preconditionFailure() + } + return String(cString: result) } public static func ipv4(fromString string: String) -> UInt32? { - let comps = string.components(separatedBy: ".") - guard comps.count == 4 else { + var addr = in_addr() + let result = string.withCString { + inet_pton(AF_INET, $0, &addr) + } + guard result > 0 else { return nil } - var ipv4: UInt32 = 0 - var bits: UInt32 = 32 - comps.forEach { - guard let octet = UInt32($0), octet <= 255 else { - return - } - bits -= 8 - ipv4 |= octet << bits - } - return ipv4 + return CFSwapInt32BigToHost(addr.s_addr) } private init() { From 9cf97250f3d6d9d6ac63d7ee954f1b14ffc36362 Mon Sep 17 00:00:00 2001 From: Davide De Rosa Date: Mon, 5 Nov 2018 20:26:39 +0100 Subject: [PATCH 2/2] Update CHANGELOG --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bd0d62..b4870b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +### Fixed + +- IPv4/UInt32 conversions are not endianness-agnostic. [#46](https://github.com/keeshux/tunnelkit/pull/46) + ## 1.3.0 (2018-10-28) ### Changed