Created
August 27, 2020 02:33
-
-
Save hisaac/c0c94b3578838427ea71b8afe6a5bd5c to your computer and use it in GitHub Desktop.
A quick and dirty playground/script to get the current device's public IP address, validate it, and print it
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
import Foundation | |
import Network | |
/// A quick and dirty playground/script to get the current device's public IP address, validate it, and print it | |
let url = URL(string: "https://checkip.amazonaws.com")! | |
var publicIPAddress: IPAddress? | |
URLSession.shared.dataTask(with: url) { (data, response, error) in | |
guard let data = data, | |
let httpResponse = response as? HTTPURLResponse, | |
200..<300 ~= httpResponse.statusCode else { | |
return | |
} | |
guard let responseString = String(data: data, encoding: .utf8) else { return } | |
var trimmedResponseString = responseString.trimmingCharacters(in: .whitespacesAndNewlines) | |
// The returned value from AWS's public IP checker can return a comma separated list of IPs. | |
// In that case, the final value is the canonical public IP, so we use that one | |
// source: https://stackoverflow.com/questions/52618096/under-what-circumstances-does-checkip-amazonaws-com-return-multiple-addresses?noredirect=1&lq=1 | |
if trimmedResponseString.contains(",") { | |
if let lastSplit = trimmedResponseString.split(separator: ",").last { | |
trimmedResponseString = String(lastSplit) | |
} | |
} | |
// Validate the returned string as an IP address | |
if let ipv4Address = IPv4Address(trimmedResponseString) { | |
print("Your IP address is an IPv4 address with the following value:", ipv4Address) | |
publicIPAddress = ipv4Address | |
} else if let ipv6Address = IPv6Address(trimmedResponseString) { | |
print("Your IP address is an IPv6 address with the following value:", ipv6Address) | |
publicIPAddress = ipv6Address | |
} else { | |
print("\(trimmedResponseString) is not a valid IP address") | |
} | |
}.resume() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment