swift 验证NSTextField中的字符串是否为有效的IP地址或域名

o2rvlv0m  于 2023-01-12  发布在  Swift
关注(0)|答案(8)|浏览(210)

我有一个NSTextField,我要求用户输入IPv4格式的字符串,或者像www.example.com这样的域名。

@IBAction func verifyTarget(sender: NSTextFieldCell) {
    var txtTarget: NSTextFieldCell = sender

    var strRawTarget: String? = txtTarget.stringValue
    println("Input: " + strRawTarget!)
    var URLTarget: NSURL?

    URLTarget = NSURL.URLWithString(strRawTarget)
    if URLTarget {
        println("URL \(URLTarget) is valid!")
    }
    else {
        println("URL \(strRawTarget) is not valid!")
    }
}

一些示例输出:

Input: 
URL  is valid!
Input: adsfasdf
URL adsfasdf is valid!
Input: afe12389hfs. . afopadsf
URL afe12389hfs. . afopadsf is not valid!
Input: 192.292.111.3
URL 192.292.111.3 is valid!
Input: 0.a.0.a
URL 0.a.0.a is valid!
Input: %2
URL %2 is not valid!
Input: %20
URL %20 is valid!

我做错什么了吗?

nwnhqdif

nwnhqdif1#

检查Swift中的IP地址是否为IPv4或IPv6

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;
}
uoifb46i

uoifb46i2#

NSURL.URLWithString根据解码相对地址或绝对地址的标准来评估您传递给它的URL字符串,这些标准在以下文档中给出:RFC 239617381808。也就是说,您希望验证的只是NSURL所能处理的一小部分。您最好使用一两个RegEx,可能来自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")
    }
}
7nbnzgx9

7nbnzgx93#

来自@Alin的代码以更紧凑的形式显示:

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() }
}

用法:

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
vjhs03f7

vjhs03f74#

新的网络框架为struct IPv4Address和struct IPv6Address提供了可失败的初始化器,它们非常容易地处理IP地址部分。在IPv6中使用正则表达式做这件事是非常坚韧的。
很遗憾,我不能解决域名部分。
请注意,Network framework是最新的,因此它可能会强制您针对最新的OS版本进行编译。

import Network
let tests = ["192.168.4.4","fkjhwojfw","192.168.4.4.4","2620:3","2620::33"]

for test in tests {
    if let _ = IPv4Address(test) {
        debugPrint("\(test) is valid ipv4 address")
    } else if let _ = IPv6Address(test) {
        debugPrint("\(test) is valid ipv6 address")
    } else {
        debugPrint("\(test) is not a valid IP address")
    }
}

output:
"192.168.4.4 is valid ipv4 address"
"fkjhwojfw is not a valid IP address"
"192.168.4.4.4 is not a valid IP address"
"2620:3 is not a valid IP address"
"2620::33 is valid ipv6 address"
hiz5n14c

hiz5n14c5#

基于@Nate Cookresponse更新为Swift 5.1

@IBAction func verifyTarget(sender: NSTextFieldCell) {
    guard let strRawTarget = sender.stringValue else { print("no input!"); return }
    print("Input: " + strRawTarget)

    if strRawTarget.isValidIpAddress {
        print("\(strRawTarget) is a valid IP address")
    } else if strRawTarget.isValidHostname {
        print("\(strRawTarget) is a valid hostname")
    } else {
        print("\(strRawTarget) is not valid")
    }
}

enum Regex {
    static let ipAddress = "^(([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])$"
    static let hostname = "^(([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])$"
}

extension String {
    var isValidIpAddress: Bool {
        return self.matches(pattern: Regex.ipAddress)
    }
    
    var isValidHostname: Bool {
        return self.matches(pattern: Regex.hostname)
    }
    
    private func matches(pattern: String) -> Bool {
        return self.range(of: pattern,
                          options: .regularExpression,
                          range: nil,
                          locale: nil) != nil
    }
}
qlfbtfca

qlfbtfca6#

@IBAction func verifyTarget(sender: NSTextFieldCell) -> Bool {
    let validIP = "^(([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])$"
    if ((sender.stringValue.count == 0) || (sender.stringValue!.range(of: validIP, options: .regularExpression) == nil)) { 
        return false 
    }
    return true
}
iezvtpos

iezvtpos7#

尝试以下内容:

private static func validate(ipAddress: String) -> Bool {
    return ipAddress.withCString({ cstring in
        var addressV6 = sockaddr_in6()
        var address = sockaddr_in()
        return inet_pton(AF_INET6, cstring, &addressV6.sin6_addr) == 1 // IPv6.
            || inet_pton(AF_INET, cstring, &address.sin_addr) == 1 // IPv4.
    });
}

只需检查sockaddr_in函数是否接受它作为IPv4地址,或者sockaddr_in6是否接受它作为IPv6地址。

vuktfyat

vuktfyat8#

我想检查字符串是否是一个IP地址或没有,我发现下面的解决方案,它的工作很好。

extension String {
    
    /// Property tells whether a string is a valid IP or not
    var isValidIpAddress: Bool {
        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 predicate = NSPredicate.init(format: "SELF MATCHES %@", validIpAddressRegex)
        let matches = predicate.evaluate(with: self)
        return matches
    }
}

用法:
string.isValidIpAddress

相关问题