Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

Network Programming Paradigms

Network Programming Paradigm

Unit-IV (15 Session)

Session 11-15 cover the following topics:-

– Network Programming Paradigm - S11-SLO1


– Socket Programming: TCP & UDP Connection oriented, connectionless – S11-SLO2
– Sock_Stream, Sock_Dgram, socket(),bind(), recvfrom(), sendto(), listen() – S12-SLO 1
– Server-Client; send(), recv(), connect(),accept(), read(), write(), close()– S12-SLO 2
– Other languages: PowerShell, Bash, TCL S13-SLO 1
– Demo: Socket Programming in Python S13-SLO2

Lab 9: Socket Programming ( Case Study) ( S14-15)

Assignment : Comparative study of Socket programming in PowerShell, Bash, TCL

TextBook:

1) John Goerzen, Brandon Rhodes, Foundations of Python Network Programming: The


comprehensive guide to building network applications with Python, 2nd ed., Kindle Edition,
2010
Introduction To Network Programming

• Computer Networking aims to study and analyze the


communication process among various computing devices or
computer systems that are linked, or networked together
• Purpose : to exchange information and share resources.

• Types
– LAN (Local Area Network)
– WAN (Wide Area Network)
– MAN (Metropolitan Area Network)
– PAN(Personal Area Network)
What is Socket?

• A socket is the most vital and fundamental entity


• Sockets are the end-point of a two-way communication link.
• An endpoint is a combination of IP address and the port
number. 
• For Client-Server communication,
– Sockets are to be configured at the two ends to initiate a
connection,
– Listen for incoming messages
– Send the responses at both ends
– Establishing a bidirectional communication.
Definition

• Sockets allow communication between processes that lie on


the same machine, or on different machines working in diverse
environment and even across different continents.
Socket Types

• Stream Sockets (SOCK_STREAM):


– Connection-oriented
– Use TCP
• Datagram Sockets (SOCK_DGRAM):
– Connectionless
– Use UDP
• Other types
– Raw Sockets
UDP Vs TCP
Features UDP-User Datagram Protocol TCP-Transmission Control
Protocol

Reliability Unreliable: no concept of Reliable:message


acknowledgment, retransmission, or acknowledgment,
timeout (as in TCP). retransmission and timeout. 

Order Not ordered: If two messages are sent Ordered: The messages are
to the same recipient, the order in delivered in a particular order
which they arrive cannot be predicted. in which they were meant to
be.

Mode of Lightweight: There is no ordering of Heavyweight: TCP requires


Transmission messages, no tracking connections, etc. three packets to set up a
Hence UDP messages are used when socket connection, before any
the rate of data transmission required is user data can be sent. The
more and reliability is not important. three packets
are: SYN, SYN+ACK and A
CK.
Create A Socket Object In Python

• sock_obj = socket.socket( socket_family, socket_type, protocol=0)


• socket_family: - Defines family of protocols used as transport
mechanism.
– Either AF_UNIX, or
– AF_INET (IP version 4 or IPv4).
• socket_type: Defines the types of communication between the two end-
points.
– SOCK_STREAM (for connection-oriented protocols, e.g., TCP), or
– SOCK_DGRAM (for connectionless protocols e.g. UDP).
• protocol: We typically leave this field or set this field to zero.
Creating a socket

#Socket client example in python


import socket
#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket Created'
Error Handling
import socket
import sys
try:
#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Failed to create socket. Error code: ' + str(msg[0]) + ' ,
Error message : ' + msg[1]
sys.exit();

print 'Socket Created'


Types Of Socket Methods In Python’s Socket Library

• Server Socket Methods,


• Client Socket Methods, and
• General Socket Methods.
Server Socket Methods
• sock_object.bind(address):
– binds the socket to address (hostname, port number pair)
• sock_object.listen(backlog):
– listen to the connections associated with the socket.
– Backlog parameter indicates maximum number of queued connections.
– Maximum value is up to 5, and minimum should be at least zero.
• sock_object.accept():
– This function returns (conn, address) pair where ‘conn’ is new socket
object used to send and receive data on the communication channel, and
‘address’ is the IP address tied to the socket on another end of the
channel.
– The ACCEPT() method returns a socket object which is different from
the socket object created using socket.socket().
– This new socket object is dedicatedly used to manage the
communication with the particular client with which accept happened.
– This mechanism also helps Server to maintain the connection with n
number of clients simultaneously.
Client Socket Methods

• sock_object.connect():
– This method is used to connect the client to host and port
– Initiate the connection towards the server.
General Socket Methods

• sock_object.recv():
– Use this method to receive messages at endpoints when the value of the
protocol parameter is TCP.
• sock_object.send():
– Apply this method to send messages from endpoints in case the protocol is TCP.
• sock_object.recvfrom():
– Call this method to receive messages at endpoints if the protocol used is UDP.
• sock_object.sendto():
– Invoke this method to send messages from endpoints if the protocol parameter
is UDP.
• sock_object.gethostname():
– This method returns hostname.
• sock_object.close():
– This method is used to close the socket. The remote endpoint will not receive
data from this side.
Python socket module

• socket.socket(family, type, proto)


– 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
Python Socket Programming WorkFlow
Socket Object Methods (Server)

• socket.bind(address)
– e.g. socket.bind((host, port))
• socket.listen(backlog)
– backlog specifies wait queue size
– e.g. socket.listen(5)
• 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
Example 1: Echo Server
Echo Client
Create a Simple Client

import socket
import sys
 # Create a TCP/IP socket
stream_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 host = 'localhost‘ # Define host
 port = 8080 # define the communication port
 # Connect the socket to the port where the server is listening
server_address = ((host, port))
 print "connecting” 
stream_socket.connect(server_address)
message = 'message‘  # Send data
stream_socket.sendall(message)
data = stream_socket.recv(10)  # response
print data
  print 'socket closed'
stream_socket.close()
Build a Simple Server

• s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
• s.bind(): Binds address (hostname, port number) to socket.
• s.listen(): Sets up and starts TCP listener.
• s.accept(): Accepts TCP client connection.

• Steps: 

– Create a socket.
– Bind the socket to a port
– Start accepting connections on the socket.
Server Program
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a TCP/IP socket
host = 'localhost‘
port = 8080
sock.bind((host, port))
sock.listen(1)
print 'waiting for a connection'
connection, client = sock.accept()
print client, 'connected'
# Receive the data in small chunks and retransmit it
data = connection.recv(16)
print 'received "%s"' % data
if data:
connection.sendall(data)
else:
print 'no data from', client
# Close the connection
connection.close()
Resources

• Useful Resources
• Python socket module documentation
• Python Network Programming Cookbook
• Simple Client-Server Example
• Packet Sniffer Example
• File Transfer Example
• Unix Sockets Tutorial
Quiz URL
https://www.techbeamers.com/python-program
ming-quiz-for-beginners-part-1/

You might also like