In this Python tutorial, let us understand the Networking – Socket Programming in Python.
Introduction of Python Networking
To access to network services, Python has two modes of operations. We can access the socket support in an operating system that allows implementing clients and servers for both connection and connection-less obligations.
Sockets are the endpoints of a bidirectional communications channel that may communicate within a process, between processes on the same machine, or between processes on different regions.
Vocabularies of Sockets
The following are socket vocabularies,
The family of protocols that are used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
Typically zero, this may be used to identify a variant of a protocol within a domain and type.
The identifier of a network interface – a string, which can be a host-name, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation
Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.
To create a socket, you must use the socket.socket() function available in socket module.
s = socket.socket (socket_family, socket_type, protocol=0)
Server Socket Methods
Client Socket Methods
A Simple Server
For writing Internet servers, need to use the socket function available to create a socket object and then it is used to call other functions to set up a socket server.
#!/usr/bin/python # This is server.py file import socket # Import socket module s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12345 # Reserve a port for your service. s.bind((host, port)) # Bind to the port s.listen(5) # Now wait for client connection. while True: c, addr = s.accept() # Establish connection with client. print 'Got connection from', addr c.send('Thank you for connecting') c.close() # Close the connection
A Simple Client
The socket.connect(hostname, port ) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file.
#!/usr/bin/python # This is client.py file import socket # Import socket module s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12345 # Reserve a port for your service. s.connect((host, port)) print s.recv(1024) s.close() # Close the socket when done
Got connection from ('127.0.0.1', 48437) Thank you for connecting