Low-level networking interface in Python (socket)


The 'socket' module in Python's standard library defines how server and client machines can communicate using socket endpoints on top of the operating system. The 'socket' API contains functions for both connection-oriented and connectionless network protocols.

Socket is an end-point of a two-way communication link. It is characterized by IP address and the port number. Proper configuration of sockets on either ends is necessary so as to initiate a connection. This makes it possible to listen to incoming messages and then send the responses in a client-server environment.

The socket() function in 'socket' module sets up a socket object.

import socket
obj = socket.socket(family, type, protocol)

The 'family' argument is AF_INET by default. Other values acceptable are: AF_INET6, AF_UNIX, AF_CAN or AF_RDS. Value of 'type' argument is by default 'SOCK_STREAM' indicating connection-oriented protocol (TCP). For connection-less protocol (UDP) set it to 'SOCK_DGRAM'. The 'protocol' argument is usually set to 0 by default.

Socket objects on the server and client are called server socket and client socket respectively. The socket object implements following methods

bind()
 This method binds the socket to specified IP address and port number.
listen()
This method starts server and runs into a listen loop looking for connection request from client.
accept()
When connection request is intercepted by server,this method accepts it and identifies the client socket with its address.

Typical server side code would be

import socket
ss = socket.socket()
ss.bind(('localhost',12345))
ss.listen()
client, addr = ss.accept()
print ("connection request from: " + str(addr))

If local machine is used as server to listen to incoming messages from same machine as client, its IP address is '127.0.0.1' also called loop back address. It is identified by the hostname of 'localhost'. The socket is made to listen at arbitrary empty port number. For communication between distant machines in a network, actual IP address must be used.

Client socket sends connection request to server socket listening at its IP address and port number

connect()

obj = socket.socket()
obj.connect((host,port))

Once connection request from client is accepted by the server, both the socket objects are now connected using TCP protocol and they can send and/or receive data.

send()

The server sends data to client by using the address it has intercepted.

client.send(bytes)

Client socket sends data to socket it has established connection with.

obj.send(bytes)

sendall()

similar to send(). This method continues to send data until either all data has been sent.

sendto()

This method is to be used in case of UDP protocol only.

recv()

This method is used to retrieve data sent to the client. In case of server, it uses the remote socket whose request has been accepted.

client.recv(bytes)

In case of client,

obj.recv(bytes)

recvfrom()

This method is used in case of UDP protocol.

Server code

import socket
host = "127.0.0.1"
port = 12345
ss = socket.socket()
ss.bind((host,port))
ss.listen()
cs, addr = server.accept()
print ("Connection from: " + str(addr))
while True:
   data = cs.recv(1024).decode()
   if not data:
      break
   print ("from connected user: " + str(data))
   print ("Received from User: " + str(data))
   data = input("type message: ")
   conn.send(data.encode())
cs.close()

Client code

import socket
host = '127.0.0.1'
port = 12345
obj = socket.socket()
obj.connect((host,port))
message = input("type message: ")
while message != 'q':
   obj.send(message.encode())
   data = obj.recv(1024).decode()
   print ('Received from server: ' + data)
   message = input("type message: ")
obj.close()

Open two command prompt windows. In one run the server code first. The in other run client code.

Updated on: 30-Jul-2019

808 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements