Check if IP is valid

From DevOps Notebook
Revision as of 10:16, 16 April 2020 by MilosZ (talk | contribs) (Created page with "Method 1: <syntaxhighlight lang="python"> import socket try: socket.inet_aton(addr) # legal except socket.error: # Not legal </syntaxhighlight> Method 2: <syntaxh...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Method 1:

import socket
try:
    socket.inet_aton(addr)
    # legal
except socket.error:
    # Not legal

Method 2:

def validate_ip(s):
    a = s.split('.')
    if len(a) != 4:
        return False
    for x in a:
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255:
            return False
    return True