Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Socket Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Socket Programming

..

Sockets
• A network socket is a virtual end point where entities can perform
inter-process communication.
• Sockets are the endpoints of a bidirectional, point-to-point
communication channel e.g. one process sitting in a computer,
exchanges data with another process sitting on the same or another
computer.
• Given an internet connection, say between client(a browser) and the
server (uz.ac.zw), we will have two sockets. A Client Socket and a
Server Socket
• The first process which initiates the communication as the client and
the latter one as the server.
• Socket acts on two parts: IP Address + Port Number
Sockets
• When you click on a link to a page, your browser does the
following:
#a socket object is created for communication:
Clientsocket =socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# now connect to the web server on port 80
# the normal http port
clientsocket.connect((“www.uz.ac.zw", 80))
Ports
• A port is an endpoint to a logical connection.
• The port number identifies what type of port it is e.g, port 80 is used
for HTTP traffic.
• Three categories of TCP and UDP ports:
Categories of ports
Well-known ports:
•Used for services that need to use specific ports.
•Ports 0–1023 are considered well-known ports because they are
used by many of the core services on the Unix servers, and most
required privilege permissions on the server to implement.
•Examples:
• Telnet (23)
• Simple Mail Transport Protocol (SMTP) (25)
•HyperText Transfer Protocol (HTTP) (80)
•File Transfer Protocol (FTP) (20 &21)
•Domain Name System (DNS) (53)
Categories of ports
Registered ports
• The Internet Assigned Numbers Authority (IANA) keeps a list of all
services that run on both the well-known ports and on all registered
ports.
• The registration process puts a permanent association in place with
the port number and the service.
• These services are all long-running services and would be assigned to
ports between 1,024 and 49,151.
• The Microsoft Remote Desktop Protocol (RDP) (3389) and Network
File System (NFS) (2049) are two examples of registered ports.
Categories of ports
Dynamic and/or private ports
• All other ports, from 49,152 to 65,535, are referred to as dynamic, or
private ports. (they are not permanently associated to any service)
• If you write your own service, you can configure it to use any dynamic
port that you want, but someone else may write his own service and
use the same port. This will not cause any issue until you install both
services on the same IP host because they are both going to want to
use the same port, and that is just not possible.
Python Sockets
• Two type of sockets:
• SOCK_STREAM [Stream Socket (TCP) ] and SOCK_DGRAM [(Datagram Socket
for UDP connection)]. Below we have a comparison of both types of
sockets
SOCK_STREAM SOCK_DGRAM
For TCP protocols For UDP protocols
Reliable delivery Unrelible delivery
Guaranteed correct ordering of
No order guaranteed
packets
Connection-oriented No notion of connection(UDP)
Bidirectional Not Bidirectional
Abstract View of Communication between
Web and Server
Creating Sockets
To create a socket, we must use:
socket.socket() function available in the Python socket module, which
has the general syntax as follows:
s = socket.socket(socket_family, socket_type, protocol=0)
• socket_family: This is either AF_UNIX or AF_INET.
• socket_type: This is either SOCK_STREAM or SOCK_DGRAM
• Protocol: This is usually left out, defaulting to 0
.

Socket Methods

Client

connect( )
• To connect to a remote socket at an address.
• An address format(host, port) pair is used for AF_INET address family
Socket Methods
Server

• bind( ): binds the socket to an address. The format of address


depends on the (AF_INET)socket family.
• listen(backlog): listens for the connection made to the socket.
The backlog is the maximum number of queued connections
that must be listened before rejecting the connection.
• accept( ): used to accept a connection. The socket must be
bound to an address and listening for connections
• The return value is a pair(conn, address) where conn is a new
socket object which can be used to send and receive data on
that connection, and address is the address bound to the socket
on the other end of the connection.
Other Socket Methods
• s.recv(): Receives TCP messages
• s.send(): Transmits TCP messages
• s.recvfrom(): Receives UDP messages
• s.sendto(): Transmits UDP messages
• close() : closes the socket connection.
• gethostname() : returns a string containing the hostname of the machine
where the python interpreter is currently executing. For example:
localhost.
• gethostbyname(): If you want to know the current machine's IP address,
you may use gethostbyname(gethostname())
Client – Server Communication through
Socket
Lets create our own sockets!
Creating a Socket
>>>import socket
>>>clientsocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

Function socket.socket creates a socket and returns a socket descriptor which


can be used in other socket related functions.
• Address Family : AF_INET ( This is for IP version of 4 or IPV4)
• Type : SOCK_STREAM ( This means connection oriented TCP protocol)
Sockets: Client Side
• When the client tries to connect with the server, a random port
is assigned by the operating system for the connection.
• This random port is called Ephermal Port.
• The client socket is short lived, i.e as soon as the data exchange ends
it closes.
• Now what happens on server is a bit different from client.
Sockets: Server Side
• >>>serversocket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
• #bind the socket to a public host and a well-known port
>>>serversocket.bind((socket.gethostname(), 80))
• #become a server socket and listen for connections
>>>serversocket.listen(5)
Sockets: Server Side
• socket(): - used to create a socket
• connect() is used by the client socket to start a connection with the
server.
• This request is fulfilled by bind method of the server socket.
• Unlike client sockets, server sockets are not short lived. For example:
you might need youtube.com for a single request but youtube.com
has to be up 24*7 for any request which it might receive from users
across the globe.
• Unlike client socket which uses Ephermal Port for connection, server
socket requires a standard or well defined port for connection.
Create TCP Client
import socket try:
import sys sock.connect((target_host,
if __name__ == '__main__': int(target_port)))
try: print("Socket Connected to %s
sock = on port: %s" %(target_host,
socket.socket(socket.AF_INET, target_port))
socket.SOCK_STREAM) sock.shutdown(2)
except socket.error as err: except socket.error as err:
print("Failed to crate a socket") print("Failed to connect to %s
print("Reason: %s" %str(err)) on port %s" %(target_host,
sys.exit(); target_port))
print('Socket created') print("Reason: %s" %str(err))
target_host = input("Enter the sys.exit();
target host name to connect: ")
target_port = input("Enter the
target port: ")
Output: Failed Connection
Socket created
Enter the target host name to connect: www.uz.ac.zw
Enter the target port: 7846
Failed to connect to www.uz.ac.zw on port 7846
Reason: [WinError 10060] A connection attempt failed because the
connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to
respond

Process finished with exit code 0


Successful Connection
Socket created
Enter the target host name to connect: www.uz.ac.zw
Enter the target port: 80
Socket Connected to www.uz.ac.zw on port: 80

Process finished with exit code 0


Create TCP client &exchange data with the server.
• The code below creates a raw HTTP client that fetches a web page
from a web server.
• It sends an HTTP GET request to pull the home page:
import socket while True:
HOST = 'www.uz.ac.zw' # or 'localhost' data = 'GET / HTTP/1.0\r\n\r\n'
PORT = 80 if not data:
BUFSIZ = 4096
break
ADDR = (HOST, PORT)
if __name__ == '__main__':
client_sock = client_sock.send(data.encode('utf-8'))
socket.socket(socket.AF_INET,socket.S data = client_sock.recv(BUFSIZ)
OCK_STREAM) if not data:
client_sock.connect(ADDR) break
print(data.decode('utf-8'))
client_sock.close()
Output
HTTP/1.1 301 Moved Permanently <title>301 Moved Permanently</title>
Date: Fri, 18 Sep 2020 04:22:07 GMT </head><body>
Server: Apache/2.4.29 (Ubuntu) <h1>Moved Permanently</h1>
Location: https://wwwbackup.uz.ac.zw/ <p>The document has moved <a
Content-Length: 319 href="https://wwwbackup.uz.ac.zw/">here<
/a>.</p>
Connection: close <hr>
Content-Type: text/html; <address>Apache/2.4.29 (Ubuntu) Server at
charset=iso-8859-1 wwwbackup.uz.ac.zw Port 80</address>
<!DOCTYPE HTML PUBLIC "-//IETF//DTD </body></html>
HTML 2.0//EN">
<html><head>

Process finished with exit code 0


TCP servers
• Server needs to bind to a socket address and listen for incoming
connections.
TCP servers
import socket • while True:
print('Server waiting for connection...')
from time import ctime client_sock, addr = server_socket.accept()
HOST = 'localhost'
print('Client connected from: ', addr)
while True:
PORT = 12345 data = client_sock.recv(BUFSIZ)
if not data or data.decode('utf-8') == 'END':
BUFSIZ = 1024 break
print("Received from client: %s" %
ADDR = (HOST, PORT) data.decode('utf-8'))
if __name__ == '__main__': print("Sending the server time to client:
%s"%ctime())
server_socket =
try:
socket.socket(socket.AF_INET,socket.SOCK_STREAM) client_sock.send(bytes(ctime(), 'utf-8'))
except KeyboardInterrupt:
server_socket.bind(ADDR) print("Exited by user")
server_socket.listen(5) client_sock.close()
server_socket.close()
server_socket.setsockopt(
socket.SOL_SOCKET,socket.SO_REUSEADDR, 1 )
Output
Server waiting for connection...
UDP Sockets
• UDP doesn't check for errors in the exchanged datagram.
• UDP client/servers are created in a similar as TCP client/servers.
• The only difference is you have to specify SOCK_DGRAM instead of
SOCK_STREAM when you create the socket object.
Create a UDP server
from socket import socket, AF_INET, SOCK_DGRAM
maxsize = 4096
sock = socket(AF_INET,SOCK_DGRAM)
sock.bind(('',12345))
while True:
data, addr = sock.recvfrom(maxsize)
resp = "UDP server sending data"
sock.sendto(resp,addr)
Create a UDP Client to send Data to Server

from socket import socket, AF_INET, SOCK_DGRAM


MAX_SIZE = 4096
PORT = 12345
ADDR = ("www.linux.org", PORT)
if __name__ == '__main__':
sock = socket(AF_INET,SOCK_DGRAM)
msg = "Hello UDP server"
sock.sendto(msg.encode(), (ADDR))
data, addr = sock.recvfrom(MAX_SIZE)
print("Server says:")
print(repr(data))
UDP Client
• The UDP client sends a single line of text Hello UDP server and
receives the response from the server.
Review Question
Write a program to do the following :
• Create a server for a port i.e. port 9000
• Permit the server to receive requests from the client
• Instruct to send the message “Hello” to the client.
• Close the socket connection

You might also like