In [1]:
import socket

In [2]:
# Print machine's name and IP Address

In [3]:
host_name = socket.gethostname()

In [4]:
host_name


Out[4]:
'gaurav-HP-Notebook'

In [5]:
ip_address = socket.gethostbyname(host_name)

In [6]:
ip_address


Out[6]:
'127.0.1.1'

In [7]:
# Retrieve a remote machine's IP Addresss

In [8]:
host = 'www.google.com'

In [9]:
socket.gethostbyname(host)


Out[9]:
'172.217.26.228'

In [10]:
# convert IPv4 Address to different format. IP address will  been converted from a string to a 32-bit packed format

In [11]:
socket.inet_aton('127.0.0.1')


Out[11]:
b'\x7f\x00\x00\x01'

In [12]:
socket.inet_ntoa(socket.inet_aton('127.0.0.1'))


Out[12]:
'127.0.0.1'

In [16]:
# Additionally, the Python hexlify function is called from
# the binascii module. This helps to represent the binary data in a hexadecimal format.

In [17]:
from binascii import hexlify

In [18]:
hexlify(socket.inet_aton('127.0.0.1'))


Out[18]:
b'7f000001'

In [19]:
# Finding a service name, given the port and protocol

In [22]:
protocolname = 'tcp'
port = 80
socket.getservbyport(port,protocolname)


Out[22]:
'http'

In [23]:
socket.getservbyport(53, 'udp')


Out[23]:
'domain'

In [24]:
# Converting integers to and from host to network byte order

In [25]:
# original data

In [3]:
data = 1234

In [27]:
# 32 bit conversion

In [28]:
# Long host byte order

In [4]:
socket.ntohl(data)


Out[4]:
3523477504

In [5]:
# Network byte order

In [6]:
socket.htonl(data)


Out[6]:
3523477504

In [7]:
# 16-bit

In [8]:
socket.ntohs(data) , socket.htons(data)


Out[8]:
(53764, 53764)

In [9]:
# Setting and getting the default socket timeout

In [11]:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

In [12]:
print(s.gettimeout())


None

In [13]:
s.settimeout(100)

In [14]:
print(s.gettimeout())


100.0

In [ ]: