Validate if a string in NSTextField is a valid IP address OR domain name
The code from @Alin in a more compact form:
extension String {
func isIPv4() -> Bool {
var sin = sockaddr_in()
return self.withCString({ cstring in inet_pton(AF_INET, cstring, &sin.sin_addr) }) == 1
}
func isIPv6() -> Bool {
var sin6 = sockaddr_in6()
return self.withCString({ cstring in inet_pton(AF_INET6, cstring, &sin6.sin6_addr) }) == 1
}
func isIpAddress() -> Bool { return self.isIPv6() || self.isIPv4() }
}
Usage:
let ipv6 = "FE80:0000:0000:0000:0202:B3FF:FE1E:8329"
let ipv6Collapsed = "FE80::0202:B3FF:FE1E:8329"
let ipv4 = "19.117.63.126"
ipv6.isIpAddress() //true
ipv6.isIPv6() //true
ipv6.isIPv4() //false
ipv6Collapsed.isIpAddress() //true
ipv6Collapsed.isIPv6() //true
ipv6Collapsed.isIPv4() //false
ipv4.isIpAddress() //true
ipv4.isIPv6() //false
ipv4.isIPv4() //true
Check if IP address is IPv4 or IPv6 in Swift
func validateIpAddress(ipToValidate: String) -> Bool {
var sin = sockaddr_in()
var sin6 = sockaddr_in6()
if ipToValidate.withCString({ cstring in inet_pton(AF_INET6, cstring, &sin6.sin6_addr) }) == 1 {
// IPv6 peer.
return true
}
else if ipToValidate.withCString({ cstring in inet_pton(AF_INET, cstring, &sin.sin_addr) }) == 1 {
// IPv4 peer.
return true
}
return false;
}
NSURL.URLWithString
evaluates the URL string you pass it based on the criteria for decoding a relative or absolute address as laid out in these not-all-that-readable documents: RFCs 2396, 1738, and 1808. That is to say, what you're hoping to validate is only a small subset of what NSURL
can handle. You're better off using a RegEx or two, perhaps from this answer:
@IBAction func verifyTarget(sender: NSTextFieldCell) {
var txtTarget: NSTextFieldCell = sender
var strRawTarget: String? = txtTarget.stringValue
println("Input: " + strRawTarget!)
let validIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
let validHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$"
if strRawTarget == nil {
println("no input!")
} else if strRawTarget!.rangeOfString(validIpAddressRegex, options: .RegularExpressionSearch) {
println("\(strRawTarget) is a valid IP address")
} else if strRawTarget!.rangeOfString(validHostnameRegex, options: .RegularExpressionSearch) {
println("\(strRawTarget) is a valid hostname")
} else {
println("\(strRawTarget) is not valid")
}
}