socket
The socket module is Python's standard interface for the transport layer.
Sockets can be classified by family
AF_INET
InternetAF_UNIX
for UNIX sockets
and type
:
- SOCK_STREAM
TCP
- SOCK_DGRAM
UDP
These enum values are required upon initialization of a socket object: [Ortega][Ortega]: 25
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Sources:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST,PORT))
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST,PORT))
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.bind((HOST,PORT))
import socket
msg = "Hello, world!"
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.sendto(msg.encode(), (HOST,PORT))
Define port on which to listen for connections.
serversocket.bind(('localhost',80))
client_socket.connect(('www.packtpub.com',80))
socket.gethostbyname('packtpub.com') # '83.166.169.231'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),1234))
socket.getservbyport(80) # 'http'
serversocket.listen(10)
msg = s.recv(1024)
print(msg.decode('utf-8'))