SOCKETS in PYTHON
References
1.Core Python Programming second Edition by Dr. R.
Nageshara Rao
2.https://www.webopedia.com/quick_ref/portnumbers.asp
3.Python socket module documentation
4.https://docs.python.org/3.4/library/socket.html
5.https://pythontic.com/modules/socket
Basics of Network
▪ Network: Is interconnections of
computers/machines/ peripherals to allow the
sharing of data, sharing of resources etc.
▪ Server: Machines that provides services
▪ Client: Machines that receive services
▪ Protocol: a set of rules to
be followed by every
machine on network
Types of Protocols
• There are two types of protocol models
based on which other protocols are
developed:
✔ TCP/IP
✔ UDP
TCP/IP MODEL
Request Server
Client
Response
NETWORK
5
IPC: as Client Server Model
⚫ Most of the interprocess communication uses the
client-server model.
⚫ Interprocess communication (IPC) refers specifically to
the mechanisms an operating system provides to allow
the processes to manage shared data
IPC approaches
❖ Files
❖ Message Passing
❖ Sockets
❖ Named Pipes etc
What is SOCKET?
• Socket is the Logical connecting point between server and
client for inter process communication on same machine or
different machines
• Each socket is given an id number called as port number.
• Port no. takes 2 bytes and can be from 0 to 65535)
Connection request
server port client
•Program for Communication of two machines through
socket is called socket programming
•Every socket created should have a new port number.
•Port numbers are allotted depending upon service provided
on socket
Socket is:
Sockets ● The endpoints of a
● The logical endpoints of a network connection
network connection ● Each host
● Each host has a unique IP address
has a unique IP address ● Each
● Given an service
id number called
runs on as port number.
a specific port ●
● Each service
Each runs on a specific
connection port
is maintained on
● both ends
Each connection by a socket
is maintained on ● Sockets
both
ends by aAPI allows us to send and receive
socket
● dataallows
Sockets API ● Programming
us to send andLanguages
provide modules and classes to use
receive data
this API
Port identifies the Socket on the Host
Application
TCP UDP
SOCKET SOCKET
2 65535
TCP 1 UDP
PORT PORT
TCP UDP
IP
Reserved port numbers and Associated services
13 Date and time services
20 FTP -- Data
21 FTP -- Control
22 SSH Remote Login Protocol Well-known ports
23 Telnet range from :
25 Simple Mail Transfer Protocol (SMTP) 0 through 1023.
53 Domain Name System (DNS)
Registered ports
80 HTTP
are 1024 to 49151.
156 SQL Server
161 SNMP Dynamic ports
443 HTTPS (also called private
444 Simple Network Paging Protocol (SNPP) ports) are 49152 to
65535.
546 DHCP Client
547 DHCP Server
https://www.webopedia.com/quick_ref/portnumbers.asp
Socket Types
● Stream Sockets (SOCK_STREAM):
○ Connection-oriented
○ Use TCP
● Datagram Sockets (SOCK_DGRAM):
○ Connectionless
○ Use UDP
● Other types:
○ E.g. Raw Sockets
Socket Programming in python
⚫ Python provides socket module/library for socket programming
⚫ For communication using TCP or UDP a program begins by
asking the OS to create an instance of the socket abstraction using
function socket()
⚫ client needs to know the existence of & the address of server
but server does not need to know the address of client prior
to connection being established
⚫ s=socket.socket(address_family, type,protocol)
Adressfamily : socket.AF_INET #(IPV4)
:socket.AF_INET6 #(IPV6)
Type: :socket.SOCK_STREAM #for TCP
:socket.SOCK_DGRAM #for UDP
Protocol: This is usually left out, defaulting to 0.
Python socket module
● socket.socket(family, type, proto)
● socket.socket()
○ Create new socket object
● socket.SOCK_STREAM (default)
● socket.SOCK_DGRAM
● socket.gethostname()
○ returns a string containing host name of the machine
● socket.gethostbyname(hostname)
○ Translates hostname to ip address
● socket.gethostbyaddr(ip_address)
○ Translates ip address to host name
Socket Object Methods
(Server)
● socket.bind(address)
○ e.g. socket.bind((host, port))
● socket.listen(size)
○ Size specifies wait queue size
○ e.g. socket.listen(5)
● Conn,adrdress= socket.accept()
○ Blocks until a client makes a connection
○ Returns (conn, address) where conn is a new socket object
usable to send and receive data
○ address is the address bound to the socket on the other end of
the connection
Socket Object Methods
● socket.connect(address) - used by client
○ e.g. socket.connect((host, port))
● socket.send(bytes, flags)
○ e.g. socket.send(b‘Hello, World!’)
● socket.recv(bufsize, flags)
○ e.g. socket.recv(1024)
○ bufsize specify maximum amount of data in bytes to be
received at once
● socket.close()
○ close connection
Socket System call for TCP
Server
Socket() Client
Bind()
Socket()
Listen()
Accept() Connect()
Data (request) from client
Recv()
Send()
Process
Request()
Data(reply) from server Recv()
Send()
bind() from socket module
⚫ For client to contact the server, the server’s
socket must have an assigned local address and
port
⚫ So the function that accomplish this is
bind().
⚫ Notice that while the client has to supply
the server ‘s address to connect(),
the server has to specify its own address
to bind().
s.bind(host,port) #here s is socket object, (host,port) is tuple
host is string containing server name
eg:’ localhost’,’www.google.co.in’
Listen()
⚫ We need to instruct the underlying TCP protocol
implementation to listen for connection from client by
calling listen() on the socket.
Listen() causes internal state changes to given socket, so
that incoming TCP connection request will be handled
and then queued for acceptance by program. The
queuelimit parameter specifies an upper bound on
number of incoming connection that can be waiting at
any time.
s.listen(5) #maximum connections allowed are 5
s is socket object
Accept()
⚫ The server gets a socket for an incoming client
connection by calling accept().
⚫ Accept() fun shall extract the first connection on
the queue of pending connection ,create a new
socket with same socket type protocol and
address family as specified socket.
⚫ c,addr= s.accept() #this method returns
connection object c used to send messages to
client and addr is address of client that has
accepted the connection
Close()
After sending the messages to client, the server
can be disconnected by closing the connection
object as
c.close()
TCP client program steps
1) import socket #import socket library
2)#create socket
s = socket.socket()
3)#get ipaddress family or hostname and assign port number
host = socket.gethostname()
port = 12221
4)#establish connect using
s.connect((host, port))
5) #print connection established
6) #take input message from user using
z=raw_input("")
7)#send data to server prgm using
s.send(z)
8)# receive data from server prgm using
s.recv(1024)
9)repeat till end of chat steps 7 and 8
TCP server program steps
1) import socket #import socket library
2) s = socket.socket() #create TCP socket
#specify internet family (ip adress and port number)
host = socket.gethostname()
print (host)
port = 12221
3)#Assign port number to socket using
s.bind((host, port))
4)#allow connection to handle the port using
s.listen(5)
5)#accept client request
c, addr = s.accept()
6) # in loop accept data from client
while (1):
print 'Got connection from', addr
data=c.recv(1024)
7) print data
8)#accept input from server program user to send to client
q = raw_input("Enter something to this client: ")
9)#send data to client program
c.send(q)
Socket system call for UDP
1
How UDP is different from TCP?
⚫ Connectionless
⚫ It does not have to be connected before
being used. E.g. mail
⚫ It can be used to send/recv msg to/from, for
that socket API provides a different sending
routine
i.e. sendto() & recvfrom().
⚫ Best effort delivery of data.
⚫ Simple to implement than TCP
SERVER: UDP
Specify socket SOCK_DGRAM
import socket
2
6
Source: www.dabeas.com
CLIENT: UDP
import socket
2
7
Source: www.dabeas.com
Sendto:
Syntax:
sendto(bytes, address)
Parameters:
bytes - The data to be sent in bytes format. If the data is in string
format, str.encode() method can be used to convert the strings to
bytes.
address - A tuple consisting of IP address and port number
The method sendto() is used to send datagrams to a UDP socket.
The communication could be from either side. It could be from
client to server or from the server to client.
For sendto() to be used, the socket should not be in already
connected state.
recvfrom:
socket.recvfrom(bufsize[, flags])
Parameters:
bufsize - The number of bytes to be read from the UDP socket.
flags - This is an optional parameter.
Return Value:
Returns a bytes object read from an UDP socket and the address
of the client socket as a tuple.
The recvfrom() method reads a number of bytes sent from
an UDP socket.
The recvfrom() method as well is to be called on a UDP socket.
The recvfrom() method can be used with an UDP server to receive
data from a UDP client or vice-versa
Sys.exit()
Use sys m
This causes the script to exit back to either the Python
console or the command prompt. This is generally used
to safely exit from the program in case of generation of
an exception.
UDP server program steps
1) import socket
import sys
2) HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
3)#create socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
4)#bind port address to ipaddres
try:
s.bind((HOST, PORT))
5) #see if error for binding socket and print error
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
6)#exit system
sys.exit()
UDP server program steps cont..
7)#now keep talking with the client
while 1:
# receive data from client (data, addr)
d = s.recvfrom(1024)
data = d[0]
addr = d[1]
8) print (data)
9)#use terminating condition
if (terminating character entered by user):
# break from while
10) #accept data from user of server program using
data1 = raw_input ("send data to UDP client:")
11)#send data to client using
s.sendto(data1 , addr)
12)print 'Message[' + addr[0] + ':' + str(addr[1]) + '] - ' + data.strip()
13) close server using
s.close()
UDP client program steps
1) #import required libraries
import socket #for sockets
import sys #for exit
2)# create dgram udp socket using
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
3)#initialze port adress and internet family(ipadress)
host = 'localhost';
port = 8888;
UDP client program steps ..cont
4) #accept input from user to be sent to server
while(1):
msg = input('Enter message to send : ')
try :
5)#send message from user to server
s.sendto(msg, (host, port))
6)#break while loop on terminating condition
7) # receive data from client (data, addr)
d = s.recvfrom(1024)
reply = d[0]
addr = d[1]
8) print data from client
9)catch exception if error
except socket.error, msg:
10) #print Error Code
11)# exit from system using
sys.exit()
12)#close socket using
s.close()
How to run
1. First Run Server
2. Then in separate window Run Client.
TCP Socket Programming
Thank You.