#! /usr/bin/env python3
import argparse
import socket
import sys


def check_ipv6(n):
    try:
        socket.inet_pton(socket.AF_INET6, n)
        return True
    except socket.error:
        return False


def check_ipv4(n):
    try:
        socket.inet_pton(socket.AF_INET, n)
        return True
    except socket.error:
        return False


def check_any(n):
    return check_ipv4(n) or check_ipv6(n)


parser = argparse.ArgumentParser(
    description='Check if an input argument is an IP address (IPv4 by default)',
    formatter_class=argparse.RawDescriptionHelpFormatter,
    epilog="Examples:\n  %(prog)s -6 ::1\n  %(prog)s 127.0.0.1\n  %(prog)s --any foo"
)
parser.add_argument('addr', type=str, nargs=1, help='Address to check')
parser.add_argument(
    '-6', dest='check', default=check_ipv4, const=check_ipv6,
    action='store_const', help='check if address is an IPv6 address'
)
parser.add_argument(
    '--any', dest='check', default=check_ipv4, const=check_any,
    action='store_const', help='check if address is a valid IPv4 or 6 address'
)
args = parser.parse_args()

if args.check(args.addr[0]):
    sys.exit(0)
else:
    sys.exit(1)
