[go: up one dir, main page]

0% found this document useful (0 votes)
33 views23 pages

NP Section 2

The document provides information about sockets in Python. It discusses that sockets are endpoints for bidirectional communication channels between clients and servers. It explains how to create sockets in Python using the socket.socket() function and the parameters needed. It also describes the different types of sockets - SOCK_STREAM for TCP and SOCK_DGRAM for UDP. Several socket methods are outlined like bind(), listen(), accept(), recvfrom(), sendto() and how they are used. Finally, examples of UDP client-server applications in Python using these methods are presented.

Uploaded by

amdmagdyabass165
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views23 pages

NP Section 2

The document provides information about sockets in Python. It discusses that sockets are endpoints for bidirectional communication channels between clients and servers. It explains how to create sockets in Python using the socket.socket() function and the parameters needed. It also describes the different types of sockets - SOCK_STREAM for TCP and SOCK_DGRAM for UDP. Several socket methods are outlined like bind(), listen(), accept(), recvfrom(), sendto() and how they are used. Finally, examples of UDP client-server applications in Python using these methods are presented.

Uploaded by

amdmagdyabass165
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Section 2

Socket Module

Created By Shreen Khalaf 3/1/2022


Basics of Sockets

 Sockets are the endpoints of a bidirectional, point-to-point


communication channel. Given an internet connection, say between
client(a browser) and the server(say studytonight.com), we will have
two sockets. A Client Socket and a Server Socket.
 Socket acts on two parts: IP Address + Port Number
 Server socket requires a standard or well defined port for connection
like: Port 80 for Normal HTTP Connection, Port 23 for Telnet etc.

Created By Shreen Khalaf 3/1/2022


Socket Module in Python

 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. We are only going to talk
about INET sockets in this tutorial, as they account for at least 99% of the
sockets in use.
 socket_type: This is either SOCK_STREAM(for TCP) or SOCK_DGRAM(for UDP).
 Protocol: This is usually left out, defaulting to 0.

Created By Shreen Khalaf 3/1/2022


Python Sockets

 There are two type of sockets: SOCK_STREAM and SOCK_DGRAM.

SOCK_STREAM SOCK_DGRAM
For TCP protocols For UDP protocols
Reliable delivery Unrelible delivery
Guaranteed correct ordering
No order guaranteed
of packets
Connection-oriented No notion of connection(UDP)
Bidirectional Not Bidirectional

Created By Shreen Khalaf 3/1/2022


Socket Functions

 gethostname():returns a string containing


the hostname of the machine where the python
interpreter is currently executing
 Gethostbyname(hostname):returns the IP address of the
host.
 getservbyname (name): returns the port number on
which the service is defined
 Getservbypor(portno): returns the name of the service
for a given port number.
Created By Shreen Khalaf 3/1/2022
Get host name and IP for host name

 gethostname() :
 Function Signature: socket.gethostname()

import socket
hostname=socket.gethostname()
print(hostname)

Created By Shreen Khalaf 3/1/2022


Gethostbyname function

 gethostbyname(): to get IP of host


 Function Signature:
 gethostbyname(hostname)
 Return Value:
 The IPv4 address of the host name provided.
 Example
ip_add=socket.gethostbyname(hostname)
print(ip_add)

Created By Shreen Khalaf 3/1/2022


Turning a Hostname into an IP Address

import socket

if __name__ == '__main__':
hostname = 'www.python.org'
addr = socket.gethostbyname(hostname)

print('The IP address of {} is {}'.format(hostname, addr))

Created By Shreen Khalaf 3/1/2022


Get port by service name and via vers

 Get port :getservbyname used to get port for specific service

 Get service by port : getservbypor

port=socket.getservbyname('domain')
print (port)

serv=socket.getservbyport(53)
print(serv)

Created By Shreen Khalaf 3/1/2022


Socket Object Methods

Server Socket Methods Client Socket


Methods
Method Description
 s.connect()
s.bind() This method binds address
(hostname, port number pair) to  This method actively initiates
socket. TCP server connection.

s.listen() This method sets up and start TCP


listener.

s.accept() This passively accept TCP client


connection, waiting until
connection arrives (blocking).

Created By Shreen Khalaf 3/1/2022


General Socket Methods

Method Description

s.recv() This method receives TCP message

s.send() This method transmits TCP message

s.recvfrom() This method receives UDP message, packet


size as argument
Return data, add
s.sendto() This method transmits UDP message

s.close() This method closes socket

Created By Shreen Khalaf 3/1/2022


bind function

 The bind() method of Python's socket class assigns an IP address and a port
number to a socket instance.
 The bind() method is used when a socket needs to be made a server socket.
 As server programs listen on published ports, it is required that a port and
the IP address to be assigned explicitly to a server socket.
 For client programs, it is not required to bind the socket explicitly to a port.
The kernel of the operating system takes care of assigning the source IP and
a temporary port number.
 Example
 s.bind(("127.0.0.1", 32007));

Created By Shreen Khalaf 3/1/2022


recvfrom() function

 The recvfrom() method Python's socket class, reads a number of bytes sent from
an UDP socket.
 The recvfrom() method can be used with an UDP server to receive data from a
UDP client or it can be used with an UDP client to receive data from a UDP server.
 Method Signature/Syntax:
 socket.recvfrom(bufsize[, flags])
 Parameters:
 bufsize - The number of bytes to be read from the UDP socket.
 flags - This is an optional parameter. As supported by the operating system.
Multiple values combined together using bitwise OR. The default value is zero.
 Return Value:
 Returns a bytes object read from an UDP socket and the address of the client socket as a
tuple.

Created By Shreen Khalaf 3/1/2022


Sendto() function

 The method sendto() of the Python's socket class, 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.
 Method Signature/Syntax:
 sendto(bytes, flags, 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.
 flags - As supported by the operating system, multiple values can be combined using bitwise
OR. This optional parameter has a default value of 0.
 address - A tuple consisting of IP address and port number.
 Return Value:
 Returns the number of bytes sent.

Created By Shreen Khalaf 3/1/2022


User Datagram Protocol (UDP)

 User Datagram Protocol (UDP) is a Transport Layer protocol.


 Unlike TCP, it is an unreliable and connectionless protocol. So, there is no
need to establish a connection prior to data transfer.
 Used for real-time services like computer gaming, voice or video
communication, live conferences;

Created By Shreen Khalaf 3/1/2022


UDP client server application

Created By Shreen Khalaf 3/1/2022


UDP server
import socket
def Server():
#Create Socket object, for UDP use SOCK_DGRAM
sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#get local machine name
host=socket.gethostname()
port=12345
server_add=(host,port)
#bind server add(ip,port) to socket
sock.bind(server_add)
while True:
print('waiting for clients')
#recive message from client recvfrom method take max data size as argement
#and return message and address of sender
data,add= sock.recvfrom(1024)
#converte the recieved bytes to string
text = data.decode('ascii')
print('recive data from',add,'data=',text)
#send data to client sendto take the message in bytes and the address that i will send the message to it
sock.sendto('replay from server'.encode('ascii'),add)
Created By Shreen Khalaf 3/1/2022
Server()
UDP Client

import socket
#Create Socket object , SOCK_DGRAM for UDP
sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#get the local machine name
host=socket.gethostname()
port=12345
server_add=(host,port)
msg='hello my first udp program'
#convert string message to bytes
msg=msg.encode('ascii')
#send the message to server
sock.sendto(msg,server_add)
#recieve message from the server, recvfrom return message and sender address
data,add= sock.recvfrom(1024)
#convert the recived bytes message to string
text = data.decode('ascii')
print('recive data from',add,'data=',text)
Created By Shreen Khalaf 3/1/2022
Encoding and Decoding

 Decoding is what happens when bytes are on their way into your application
and you need to figure out what they mean.
 Encoding is the process of taking character strings that you are ready to
present to the outside world and turning
them into bytes

Created By Shreen Khalaf 3/1/2022


Broadcast

 Use setsockopt() method to turn on broadcast.

sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

 Instead of using the ip for host we use "<broadcast>",


 The level argument specifies the protocol level at which the option resides.
To set options at the socket level, specify the level argument as
SOL_SOCKET. To set options at other levels, supply the
appropriate level identifier for the protocol controlling the option. For
example, to indicate that an option is interpreted by the TCP, set level to
IPPROTO_TCP

Created By Shreen Khalaf 3/1/2022


UDP client broadcast

import socket

def client(ip,port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
text = 'Broadcast datagram!'
sock.sendto(text.encode('ascii'), (ip, port))
msg, add = sock.recvfrom(1024)
msg = msg.decode('ascii')
print(add,msg)

client("<broadcast>",12345)

Created By Shreen Khalaf 3/1/2022


Task1

 Create UPD broad cast server to send message to any client

Created By Shreen Khalaf 3/1/2022


Created By Shreen Khalaf 3/1/2022

You might also like