1#!/usr/bin/env python3
 2
 3"""IP address helper functions.
 4"""
 5
 6
 7
 8import socket
 9import subprocess
10
11class NetworkError(Exception):
12    pass
13
14class UnknownServer(NetworkError):
15    pass
16
17
18def is_ip_address(s):
19    """Check if `s` is an IP address in the form 'aaa.bbb.ccc.ddd'"""
20
21    try:
22        socket.inet_aton(s)
23        return True
24
25    except socket.error:
26        return False
27
28
29def reverse_ip(s):
30    """Perform a reverse IP lookup on `s`"""
31
32    return socket.gethostbyaddr(s)[0]
33
34
35def lookup_ip(s):
36    """Lookup IP address of host `s`"""
37    try:
38        return socket.gethostbyname(s)
39    except socket.gaierror:
40        raise UnknownServer(s)
41
42
43def ping(host):
44    """Ping `host`. Returns True is everything is ok otherwise an error string."""
45
46    res = subprocess.Popen('ping -c 1 {host}'.format(host=host),
47                          shell=True,
48                          stdout=open('/dev/null', 'w'),
49                          stderr=subprocess.PIPE)
50    _, err = res.communicate()
51
52    if res.returncode == 0:
53        return True
54
55    else:
56        return err