Created
August 1, 2018 18:43
-
-
Save mrmitew/8eb86ec57d8240d3fc2808a754c17842 to your computer and use it in GitHub Desktop.
Extension functions for NetService and NSData that provide an easy way to get IPV4 as String from any resolved NetService
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example usage can be found in the following repository: https://github.com/mrmitew/Bonjour-iOS | |
extension NetService { | |
func getIpV4() -> String? { | |
if let ipData = self.addresses?.first { | |
return (ipData as NSData).getIpV4() | |
} | |
return nil | |
} | |
} | |
extension NSData { | |
func getIpV4(port: Int? = nil) -> String { | |
var ip1 = UInt8(0) | |
getBytes(&ip1, range: NSMakeRange(4, 1)) | |
var ip2 = UInt8(0) | |
getBytes(&ip2, range: NSMakeRange(5, 1)) | |
var ip3 = UInt8(0) | |
getBytes(&ip3, range: NSMakeRange(6, 1)) | |
var ip4 = UInt8(0) | |
getBytes(&ip4, range: NSMakeRange(7, 1)) | |
if port != nil { | |
return String(format: "%d.%d.%d.%d:%d", ip1, ip2, ip3, ip4, port!) | |
} else { | |
return String(format: "%d.%d.%d.%d", ip1, ip2, ip3, ip4) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment