Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用 正则匹配 判断是否为ipv4/6的性能和算法实现的性能差别还是挺大的 #14

Closed
oldthreefeng opened this issue Sep 7, 2020 · 2 comments
Assignees

Comments

@oldthreefeng
Copy link
Contributor

推荐一个leecode上的大佬写的.

func isIPV4(IP string) bool {
    arr := strings.Split(IP, ".")
    if len(arr) != 4 {
        return false
    }
    for _, elem := range arr {
        if elem == "" {
            return false
        }
        if len(elem) > 1 && elem[0] == '0' {
            return false
        }
        num := 0
        for _, c := range elem {
            if c >= '0' && c <= '9' {
                num = num*10 + int(c - '0')
            }else{
                return false
            }
        }
        if num > 255 {
            return false
        }
    }
    return true
}

//IPV6地址的判断:
//1. 用“:”分割字符串,若长度不等于8,则return Neither
//2. 遍历每一个数组的每一个元素,若元素的长度大于4,则return Neither
//3. 判断每一个元素的字符,若出现非0-9,A-F的字符,则return Neither
func isIPV6(IP string) bool {
    IP = strings.ToUpper(IP)
    arr := strings.Split(IP, ":")
    if len(arr) != 8 {
        return false
    }
    for _, elem := range arr {
        if elem == "" || len(elem) > 4{
            return false
        }
        
        for _, c := range elem {
            if (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'){
                continue
            }else{
                return false
            }
        }
    }
    return true
}
@zu1k
Copy link
Owner

zu1k commented Sep 7, 2020

ipv4的没问题,ipv6覆盖的不全啊

@zu1k zu1k self-assigned this Sep 7, 2020
@oldthreefeng
Copy link
Contributor Author

ipv6的没考虑到省略写法..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants