In [1]:
import socket
print(socket.gethostname())
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))
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()
In [6]:
domain_name = 'www.python.org'
print('{}:{}'.format(domain_name, socket.getfqdn(domain_name)))
In [7]:
hostname, aliases, address = socket.gethostbyaddr('127.0.0.1')
print(' Hostname', hostname)
print(' aliases', aliases)
print(' address', addresses)
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))
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)
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)))
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()
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()