1 Host


In [1]:
import socket
print(socket.gethostname())


gaofeng.local

In [2]:
HOSTS = [
    'apu',
    'gaufung.me',
    'www.python.org'
]
for host in HOSTS:
    try:
        print('{}:{}'.format(host, socket.gethostbyname(host)))
    except socket.error as msg:
        print('{}:{}'.format(host,msg))


apu:[Errno 8] nodename nor servname provided, or not known
gaufung.me:119.28.1.66
www.python.org:151.101.76.223

In [3]:
for host in HOSTS:
    print(host)
    try:
        name, aliases, addresses = socket.gethostbyname_ex(host)
        print('  Hostname', name)
        print('  Aliases', aliases)
        print('  Addresses', addresses)
    except socket.error as msg:
        print(' Error', msg)
    print()


apu
 Error [Errno 8] nodename nor servname provided, or not known

gaufung.me
  Hostname gaufung.me
  Aliases []
  Addresses ['119.28.1.66']

www.python.org
  Hostname python.map.fastly.net
  Aliases ['www.python.org']
  Addresses ['151.101.76.223']


In [6]:
domain_name = 'www.python.org'
print('{}:{}'.format(domain_name, socket.getfqdn(domain_name)))


www.python.org:www.python.org

In [7]:
hostname, aliases, address = socket.gethostbyaddr('127.0.0.1')
print(' Hostname', hostname)
print(' aliases', aliases)
print(' address', addresses)


 Hostname localhost
 aliases ['1.0.0.127.in-addr.arpa']
 address ['151.101.76.223']

2 Find Server Infomation


In [10]:
import socket
from urllib.parse import urlparse
URLS = [
    'http://www.python.org',
    'https://www.mybank.com',
    'ftp://prep.ai.mit.edu',
    'gopher://gopher.micro.umn.edu',
    'smtp://mail.example.com',
    'imap://mail.example.com',
    'imaps://mail.example.com',
    'pop3://pop.example.com',
    'pop3s://pop.example.com',
]
for url in URLS:
    parsed_url = urlparse(url)
    port = socket.getservbyname(parsed_url.scheme)
    print('{:>6}:{}'.format(parsed_url.scheme, port))


  http:80
 https:443
   ftp:21
gopher:70
  smtp:25
  imap:143
 imaps:993
  pop3:110
 pop3s:995

In [11]:
import socket
from urllib.parse import urlunparse

for port in [80, 443, 21, 70, 25, 143, 993, 110, 995]:
    url = '{}://example.com/'.format(socket.getservbyport(port))
    print(url)


http://example.com/
https://example.com/
ftp://example.com/
gopher://example.com/
smtp://example.com/
imap://example.com/
imaps://example.com/
pop3://example.com/
pop3s://example.com/

In [14]:
import socket
def get_constant(prefix):
    return {
        getattr(socket, n):n
        for n in dir(socket)
        if n.startswith(prefix)
    }
protocals = get_constant('IPPROTO_')
for name in ['icmp','udp','tcp']:
    proto_num = socket.getprotobyname(name)
    const_name = protocals[proto_num]
    print('{:>4} -> {:2d} (socket.{:<12} = {:2d})'.format(
        name, proto_num, const_name,
        getattr(socket, const_name)))


icmp ->  1 (socket.IPPROTO_ICMP =  1)
 udp -> 17 (socket.IPPROTO_UDP  = 17)
 tcp ->  6 (socket.IPPROTO_TCP  =  6)

3 Looking Up Server Addresses


In [16]:
import socket

def get_constants(prefix):
    """Create a dictionary mapping socket module
    constants to their names.
    """
    return {
        getattr(socket, n): n
        for n in dir(socket)
        if n.startswith(prefix)
    }
families = get_constants('AF_')
types = get_constants('SOCK_')
protocols = get_constants('IPPROTO_')
for response in socket.getaddrinfo('www.python.org', 'http'):

    # Unpack the response tuple
    family, socktype, proto, canonname, sockaddr = response

    print('Family        :', families[family])
    print('Type          :', types[socktype])
    print('Protocol      :', protocols[proto])
    print('Canonical name:', canonname)
    print('Socket address:', sockaddr)
    print()


Family        : AF_INET
Type          : SOCK_DGRAM
Protocol      : IPPROTO_UDP
Canonical name: 
Socket address: ('151.101.76.223', 80)

Family        : AF_INET
Type          : SOCK_STREAM
Protocol      : IPPROTO_TCP
Canonical name: 
Socket address: ('151.101.76.223', 80)

Family        : AF_INET6
Type          : SOCK_DGRAM
Protocol      : IPPROTO_UDP
Canonical name: 
Socket address: ('2a04:4e42:12::223', 80, 0, 0)

Family        : AF_INET6
Type          : SOCK_STREAM
Protocol      : IPPROTO_TCP
Canonical name: 
Socket address: ('2a04:4e42:12::223', 80, 0, 0)

4 IP Address Representations


In [19]:
import binascii
import socket
import struct
import sys

for string_address in ['192.168.1.1', '127.0.0.1']:
    packed = socket.inet_aton(string_address)
    print('Original:', string_address)
    print('Packed  :', binascii.hexlify(packed))
    print('Unpacked:', socket.inet_ntoa(packed))
    print()


Original: 192.168.1.1
Packed  : b'c0a80101'
Unpacked: 192.168.1.1

Original: 127.0.0.1
Packed  : b'7f000001'
Unpacked: 127.0.0.1