> For the complete documentation index, see [llms.txt](https://imhuay.gitbook.io/studies/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://imhuay.gitbook.io/studies/algorithms/problems/2022/05/niu-ke-0113-zhong-deng-yan-zheng-ip-di-zhi.md).

# 验证IP地址

![last modify](https://img.shields.io/static/v1?label=last%20modify\&message=2022-10-14%2014%3A59%3A33\&color=yellowgreen\&style=flat-square) [![](https://img.shields.io/static/v1?label=\&message=%E4%B8%AD%E7%AD%89\&color=yellow\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/05/pages/R5NyOzkn3qAZy7wCx1pS#中等) [![](https://img.shields.io/static/v1?label=\&message=%E7%89%9B%E5%AE%A2\&color=green\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/05/pages/R5NyOzkn3qAZy7wCx1pS#牛客) [![](https://img.shields.io/static/v1?label=\&message=%E5%AD%97%E7%AC%A6%E4%B8%B2\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/05/pages/R5NyOzkn3qAZy7wCx1pS#字符串)

> [验证IP地址\_牛客题霸\_牛客网](https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880)

**问题简述**

```
编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址；

IPv4 地址由十进制数和点来表示，每个地址包含4个十进制数，其范围为 0 - 255， 用(".")分割。比如，172.16.254.1；
同时，IPv4 地址内的数不会以 0 开头。比如，地址 172.16.254.01 是不合法的。

IPv6 地址由8组16进制的数字来表示，每组表示 16 比特。这些组数字通过 (":")分割。比如,  2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且，我们可以加入一些以 0 开头的数字，字母可以使用大写，也可以是小写。所以， 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即，忽略 0 开头，忽略大小写)。

然而，我们不能因为某个组的值为 0，而使用一个空的组，以至于出现 (::) 的情况。 比如， 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。
同时，在 IPv6 地址中，多余的 0 也是不被允许的。比如， 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。

说明: 你可以认为给定的字符串里没有空格或者其他特殊字符。
```

**思路**

* 内置函数 `int(s, n)`：将字符串 s 按 n 进制转化；

<details>

<summary><strong>Python</strong></summary>

```python
class Solution:
    def solve(self , IP: str) -> str:
        
        def is_ipv4(ip):
            ps = ip.split('.')
            if len(ps) != 4: return False
            for p in ps:
                if p.startswith('0') and len(p) > 1: return False  # 存在前导 0 且长度大于 1
                try: 
                    if not 0 <= int(p) <= 255: return False
                except: 
                    return False
            return True
        
        def is_ipv6(ip):
            ps = ip.split(':')
            if len(ps) != 8: return False
            for p in ps:
                if len(p) > 4 or len(p) == 0: return False  # 长度大于 4 或为空
                try: 
                    _ = int(p, 16)  # 16进制转十进制
                except: 
                    return False
            return True
        
        if is_ipv4(IP): return 'IPv4'
        elif is_ipv6(IP): return 'IPv6'
        else: return 'Neither'
```

</details>
