0% found this document useful (0 votes)
5 views

NWProg S23

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)
5 views

NWProg S23

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/ 58

Dr.

Hatem Yousry
Network Programming
Network Programming 1
Dr. Hatem Yousry
Agenda
• Addressing,
• Handling IPv4 addresses.

Dr. Hatem Yousry


• Handing IPv6 addresses.
• The Socket Module
• Server Socket Methods

Network Programming
• Client Socket Methods

2
What is Network Programming?
• Network programs: Programs that use network in some way to do
their work.
• Send/receive data across a network

Dr. Hatem Yousry


• Provide/invoke services over a network
• Mobile computing through wireless networks
• Cloud/edge computing

Network Programming
• Network programming is the discipline of designing and
implementing network programs.

3
The Key Players

• Server (Service provider)


• A program that provides data and/or services to other

Dr. Hatem Yousry


programs a computer that manages a network resource
file server, Web server, database server, mail server, …
• Client (Service consumer)

Network Programming
• A program that relies on another program for some of
its data or services Web browser, email client, ...
• Protocols
• An agreed-upon way of exchanging info and service
requests between clients and servers
4
Three Main Issues
• Addressing
• Specifying a remote computer and service

Dr. Hatem Yousry


• Data transport
• Moving data(bits) back and forth
• Meaningful conversation

Network Programming
• Conversation in proper order
• Understand each other

5
Networking Address
• Machines have a hostname and IP address
• Programs/services have port numbers

Dr. Hatem Yousry


• Use application protocol modules for corresponding services.
• Consider using threads , concurrency , asyncio , and selectors
modules for handling multiple connections in parallel.

Network Programming
6
Internet Addresses
• The current IPv4 addresses ( 32 bit ) is about to
running out.

Dr. Hatem Yousry


• The new IPv6 addresses are 128 bit values (over
3.4 * 1038 unique addresses) and are represented
as 8 hexadecimal numbers each representing a 16

Network Programming
bit value.
• FEDC:BA98:7654:3210:FEDC:BA98:7654:3210
• Read RFC 2373
http:///www.letf.org/rfc/rfc2373.txt ) for more
7
information.
Internet Protocol version 4 (IPv4)
• Internet Protocol version 4 (IPv4) is the fourth version of the
Internet Protocol (IP). It is one of the core protocols of
standards-based internetworking methods in the Internet and
other packet-switched networks.
• Packets in the IPv4 layer are called datagrams.
• A datagram is a variable-length packet consisting of two
parts: header and data.
• The header is 20 to 60 bytes in length and contains
information essential to routing.
• Version (VER): This 4-bit field defines the version of the IPv4
protocol.
• IPv4 uses 32-bit addresses which limits the address space to 8
4294967296 (232) addresses.
Internet Protocol version 4 (IPv4) datagrams

• Packets in the IPv4 layer are called datagrams. A datagram is a


variable-length packet consisting of two parts: header and
data.

9
Internet Protocol Version 6 (IPv6)
• Internet Protocol version 6 (IPv6) is the most recent version of the
Internet Protocol (IP), the communications protocol that provides an
identification and location system for computers on networks and
routes traffic across the Internet.
• The previous version, IPv4, uses a 32-bit addressing scheme to
support 4.3 billion devices, which was thought to be enough.
• However, the growth of the internet, personal computers,
smartphones and now Internet of Things (IoT) devices proves
that the world needed more addresses.
• Fortunately, the Internet Engineering Task Force (IETF) recognized
this 20 years ago. In 1998 it created IPv6, which instead uses 128-bit
addressing to support approximately 340 trillion (or 2 to the 128th
power, if you like).
• Instead of the IPv4 address method of four sets of one- to three-digit
numbers, IPv6 uses eight groups of four hexadecimal digits, 10
separated by colons.
Internet Protocol Version 6 (IPv6)

11
12
13
14
15
16
Why is there no IPv5?
• There was an IPv5 that was also known as Internet Stream
Protocol, abbreviated simply as ST. It was designed for
connection-oriented communications across IP networks
with the intent of supporting voice and video.
• One shortcoming that undermined its popular use was its 32-
bit address scheme – the same scheme used by IPv4. As a
result, it had the same problem that IPv4 had – a limited
number of possible IP addresses. That led to the development
and eventual adoption of IPv6.
• Even though IPv5 was never adopted publicly, it had used up
the name IPv5.
17
Python Networking Levels
• Python provides two levels of access to network
services.

Dr. Hatem Yousry


• Low level : can access the basic socket support in
the underlying OS
• Connection Oriented - SOCK_STREAM

Network Programming
• Connectionless - SOCK_DGRAM
• High level protocol level libraries for various
application level network protocols
• FTP, HTTP, POP3, SMTP, … 18
Connections
• Each endpoint of a network connection is
• always represented by a host and port #
• In Python you write it out as a tuple (host, port)

Dr. Hatem Yousry


("www.python.org", 80)
("205.172.13.4", 80)
• In almost all of the network programs you’ll write, you use this

Network Programming
convention to specify a network address

19
Data Transport
• There are two basic types of communication
• Streams TCP:
• Computers establish a connection with each other and read/write data

Dr. Hatem Yousry


in a continuous stream of bytes like a file. This is the most common.
• Datagrams UDP:
• Computers send discrete packets (or messages ) to each other. Each

Network Programming
packet contains a collection of bytes, but each packet is separate
and self contained.
• The type of communications between the two endpoints, typically
SOCK_STREAM for connection-oriented protocols and
SOCK_DGRAM for connectionless protocols.

20
Connectionless vs. Connection-oriented
packet switched services
• Datagram or Connectionless.
• Virtual circuit or Connection-oriented.
• Connection Oriented Services: It can generate an end to end
connection between the senders to the receiver before sending the
data over the same or multiple networks.
• Connectionless Services: It can transfer the data packets between
senders to the receiver without creating any connection.

21
TCP versus UDP
• Different services use different packet transmission techniques.
• In general, packets that must get through in the correct
order, without loss, use TCP, whereas real time services
where later packets are more important than older packets
use UDP.
• For example, file transfer requires complete accuracy and so is
normally done using TCP, and audio conferencing is frequently
done via UDP, where momentary glitches may not be noticed.
• UDP lacks built-in network congestion avoidance and the
protocols that use it must be extremely carefully designed to
prevent network collapse.
22
Sockets
• Programming abstraction for network code
• Socket : A communication endpoint

Dr. Hatem Yousry


Network Programming
• Supported by socket library module
• Allows connections to be made and data to be transmitted in
either direction

23
Python Socket Support
• Python supports socket networking through the socket module.
• The module provides the Berkeley Software Distribution (BSD)
socket interface.

Dr. Hatem Yousry


• The BSD sockets application programming interface (API) is a set of
standard function calls that can be used in an application.
• The socket() function create socket objects.

Network Programming
• Various functions( gethostbyname (), gethostbyaddr () …) to get
Comm related info.
• The send()/ recv () function send/receive data through the socket.

24
What is Sockets?
• Sockets are the endpoints of a bidirectional
communications channel.
• Sockets may communicate within a process, between processes

Dr. Hatem Yousry


on the same machine, or between processes on different
continents.
• Sockets may be implemented over a number of different

Network Programming
channel types: Unix domain sockets, TCP, UDP, and so on.
The socket library provides specific classes for handling the
common transports as well as a generic interface for handling
the rest.

25
Socket Programming
• A socket is a communications
connection point (endpoint) that you
can name and address in a network.

Dr. Hatem Yousry


• Socket programming is a way of
connecting two nodes on a network
to communicate with each other.

Network Programming
• One socket(node) listens on a
particular port at an IP, while the
other socket reaches out to the
other to form a connection.
• The server forms the listener socket
while the client reaches out to the 26
server.
Network Programming Dr. Hatem Yousry
27
Network Programming Dr. Hatem Yousry
28
The Socket Module
Sr.
Term & Description
No.
Domain
1 The family of protocols that is used as the transport mechanism. These values are constants such as

Dr. Hatem Yousry


AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.

type
2 The type of communications between the two endpoints, typically SOCK_STREAM for
connection-oriented protocols and SOCK_DGRAM for connectionless protocols.

Network Programming
protocol
3
Typically zero, this may be used to identify a variant of a protocol within a domain and type.
hostname
The identifier of a network interface −
•A string, which can be a host name, a dotted-quad address, or an IPV6 address in colon (and
4 possibly dot) notation
•A string "<broadcast>", which specifies an INADDR_BROADCAST address.
•A zero-length string, which specifies INADDR_ANY, or
•An Integer, interpreted as a binary address in host byte order.
29
port
5 Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a
string containing a port number, or the name of a service.
The Socket Module
• To create a socket, you must use the socket.socket() function
available in socket module, which has the general syntax −
• s = socket.socket (socket_family, socket_type, protocol=0)

Dr. Hatem Yousry


• Here is the description of the parameters −
• socket_family − This is either AF_UNIX or AF_INET.

Network Programming
• socket_type − This is either SOCK_STREAM or
SOCK_DGRAM.
• protocol − This is usually left out, defaulting to 0.
• Once you have socket object, then you can use required
functions to create your client or server program.
30
The Socket Module
• import socket
• s = socket.socket(socket.AF_INET,

Dr. Hatem Yousry


socket.SOCK_STREAM)
• print(s)

Network Programming
<socket.socket fd=3, family=AddressFamily.AF_INET,
type=SocketKind.SOCK_STREAM, proto=0,
laddr=('0.0.0.0', 0)>

31
Server Socket Methods
Client Socket Methods
Sr.No
Method & Description
.

Dr. Hatem Yousry


s.bind()
1
This method binds address (hostname, port number pair) to socket.
s.listen()
2
This method sets up and start TCP listener.

Network Programming
s.accept()
3 This passively accept TCP client connection, waiting until connection
arrives (blocking).

Sr.No
Method & Description
.
32
s.connect()
1
This method actively initiates TCP server connection.
General Socket Methods
Sr.No
Method & Description
.
s.recv()

Dr. Hatem Yousry


1
This method receives TCP message
s.send()
2
This method transmits TCP message

Network Programming
s.recvfrom()
3
This method receives UDP message
s.sendto()
4
This method transmits UDP message
s.close()
5
This method closes socket
socket.gethostname() 33
6
Returns the hostname.
A Simple Server
• A server has a bind() method which binds it to a specific IP
and port so that it can listen to incoming requests on that IP
and port.

Dr. Hatem Yousry


• A server has a listen() method which puts the server into
listening mode. This allows the server to listen to incoming
connections.

Network Programming
• And last a server has an accept() and close() method. The
accept method initiates a connection with the client and the
close method closes the connection with the client.

34
• # first of all import the socket library
• import socket
• # next create a socket object
• s = socket.socket()
• print ("Socket successfully created")
• # reserve a port on your computer in our case it is 40674 but it can be anything
• port = 40674
• # Next bind to the port
• # we have not typed any ip in the ip field instead we have inputted an empty string this makes

Dr. Hatem Yousry


the server listen to requests coming from other computers on the network
• s.bind(('', port))
• print ("socket binded to %s" %(port))
• # put the socket into listening mode
• s.listen(5)

Network Programming
• print ("socket is listening")
• # a forever loop until we interrupt it or an error occurs
• while True:
• # Establish connection with client.
• c, addr = s.accept()
• print ('Got connection from', addr )
• # send a thank you message to the client.
• c.send(b'Thank you for connecting')
• # Close the connection with the client
35
• c.close()
A Simple Server
• We made a socket object and reserved a port on our pc.
• After that, we bound our server to the specified port.

Dr. Hatem Yousry


• Passing an empty string means that the server can listen to
incoming connections from other computers as well. If we
would have passed 127.0.0.1 then it would have listened to
only those calls made within the local computer.

Network Programming
• After that, we put the server into listening mode. 5 here means
that 5 connections are kept waiting if the server is busy and
if a 6th socket tries to connect then the connection is
refused.
• At last, we make a while loop and start to accept all
incoming connections and close those connections after a 36
thank you message to all connected sockets.
Start the Server
• Now we need something with which a server can interact.
• We could tenet to the server like this just to know that our

Dr. Hatem Yousry


server is working. Type these commands in the terminal:
• # start the server
• python server.py
• # keep the above terminal open

Network Programming
• # now open another terminal and type:
• telnet localhost 12345

37
A Simple Client
• # Import socket module
• import socket

• # Create a socket object

Dr. Hatem Yousry


• s = socket.socket()

• # Define the port on which you want to connect


• port = 40674

Network Programming
• # connect to the server on local computer
• s.connect(('127.0.0.1', port))

• # receive data from the server


• print(s.recv(1024))

• # close the connection


• s.close() 38
A Simple Client
• We connect to localhost on port 40674 (the port on which our
server runs) and lastly, we receive data from the server and
close the connection.

Dr. Hatem Yousry


• Now save this file as client.py and run it from the terminal
after starting the server script.

Network Programming
39
A Simple Client/Server
• Now run this server.py in background and then run above
client.py to see the result.
• # Following would start a server in background.

Dr. Hatem Yousry


• $ python server.py &
• # Once server is started run client as follows:
• $ python client.py

Network Programming
• This would produce following result −
• Got connection from ('127.0.0.1', 40674)

40
Protocols
• Send/receive data back and forth is meaningless if we can’t
understand each other.
• To conduct meaningful conversation

Dr. Hatem Yousry


• Follow agreed upon rules of message exchange
• Provide data in proper format
• Python offers protocol modules for many networking

Network Programming
tasks/applications.

41
Python Internet modules
• A list of some important modules in Python Network/Internet
programming.

Dr. Hatem Yousry


Protocol Common function Port No Python module

HTTP Web pages 80 httplib, urllib, xmlrpclib

NNTP Usenet news 119 nntplib

Network Programming
FTP File transfers 20 ftplib, urllib

SMTP Sending email 25 smtplib

POP3 Fetching email 110 poplib

IMAP4 Fetching email 143 imaplib

Telnet Command lines 23 telnetlib 42

Gopher Document transfers 70 gopherlib, urllib


TCP-IP Network Services
• Port numbers such as List of TCP and UDP port numbers.
• Many Internet Protocol-based services are associated with a
particular well-known port number which is standardized by the
Internet technical governance.
• For example, World-Wide-Web servers operate on port 80, and
email relay servers usually listen on port 25.

43
Multi Server Simulator
Create Virtual Test Networks

Dr. Hatem Yousry


Network Programming
44

https://www.paessler.com/tools/serversimulator
Multi Server Simulator
• The program will automatically discover all available IP
addresses on the local machine. Select an IP address and click
on one of the protocol buttons to add a virtual server. It will

Dr. Hatem Yousry


show up in the tree view on the right, beneath its IP address.
Click a server to go to the configuration settings. When done
with the configuration enable the "Up/Down" checkbox to start

Network Programming
the server.

45
Multi Server
Simulator
• Using a standard Windows PC you can create large virtual networks
using Multi Server Simulator. You are able to create as many servers
and virtual switches as desired - limited only by the number of

Dr. Hatem Yousry


available IP addresses and TCP ports (as well as network and system
performance).
• Available Virtual Device Types:
• SNMP based switches (with 8, 100 or 1000 switch ports each)

Network Programming
• HTTP server
• FTP server
• SMTP server
• DNS server
• Simple server (open TCP port that accepts connections)
• Setting up a network 100 servers and 20 switches (with thousands of
ports) network merely takes a few minutes, much faster than 46
installing and configuring normal server software on a PC.
Multi Server
Simulator
• LICENSE DETAILS
• License Name: prtgtrial

Dr. Hatem Yousry


• License Key:
• 000014-Y8JKFM-8FFZ0D-3CYMMX-T47VF0-60CY8W-
N9UM5A-QW3NDH-VCVAVX-8354M9
https://www.paessler.com/tools/serversimulator

Network Programming
47
Server - msg
• import socket
• s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
• s.bind((socket.gethostname(), 1234))

Dr. Hatem Yousry


• s.listen(5)
• while True:
• # now our endpoint knows about the OTHER endpoint.

Network Programming
• clientsocket, address = s.accept()
• print(f"Connection from {address} has been established.")
• clientsocket.send(bytes("Hey there!!!","utf-8"))
• clientsocket.close()

48
Client- msg
• import socket
• s = socket.socket(socket.AF_INET,

Dr. Hatem Yousry


socket.SOCK_STREAM)
• s.connect((socket.gethostname(), 1234))
• full_msg = ''
• while True:

Network Programming
• msg = s.recv(8)
• if len(msg) <= 0:
• break
• full_msg += msg.decode("utf-8")
• print(full_msg) 49
Simple Calculator in Python Socket
Programming
• First, we will write client-side code. A client is a user or machine
which generates a request to the server in return it gets the response
from the server side. To perform these tasks we have to know two

Dr. Hatem Yousry


things which are the Port Number and IP Address of the Server.
• In this case, We will use localhost IP which is 127.0.0.1 and the port
number is “8080”.
• The server-side is a machine on which all the operations are executed

Network Programming
as requested by the client-side, we will perform addition, subtraction,
multiplication, and division operation on the server. To do so the
server received input from a client and performs the basic operation
by itself. when the result is ready Python server then sends the output
to the client machine.

50
Python
The Server-side
• # Import socket module
• import socket
• # Here we use localhost ip address and port number

Dr. Hatem Yousry


LOCALHOST = "127.0.0.1"
• #LOCALHOST = socket.gethostname()
• PORT = 8081
• # calling server socket method
• server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

Network Programming
server.bind((LOCALHOST, PORT))
• server.listen(5)
• print("Server started")
• print("Waiting for client request..")
• # Here server socket is ready for get input from the user
• clientConnection, clientAddress = server.accept()
• print("Connected client :", clientAddress)
• msg = ''
51
The Server-side
• # Running infinite loop
• while True:
• data = clientConnection.recv(1024)
• msg = data.decode()

Dr. Hatem Yousry


• if msg == 'Over':
• print("Connection is Over")
• break

Network Programming
print("Equation is received")
• result = 0
• operation_list = msg.split()
• oprnd1 = operation_list[0]
• operation = operation_list[1]
• oprnd2 = operation_list[2]

• # here we change str to int converstion


• num1 = int(oprnd1) 52
• num2 = int(oprnd2)
The Server-side
• # Here we are perform basic arithmetic operation
• if operation == "+":
• result = num1 + num2
• elif operation == "-":

Dr. Hatem Yousry


• result = num1 - num2
• elif operation == "/":
• result = num1 / num2

Network Programming
elif operation == "*":
• result = num1 * num2

• print("Send the result to client")


• # Here we change int to string and
• # after encode send the output to client
• output = str(result)
• clientConnection.send(output.encode())
• clientConnection.close() 53
Client-side code
• # Import socket module
• import socket

Dr. Hatem Yousry


• # In this Line we define our local host address with port
number
• SERVER = "127.0.0.1"

Network Programming
• PORT = 8081
• # Making a socket instance
• client = socket.socket(socket.AF_INET,

socket.SOCK_STREAM)
• # connect to the server 54
• client.connect((SERVER, PORT))
Client-side code
• # Running a infinite loop
• while True:
• print("Example : 4 + 5")
• # here we get the input from the user

Dr. Hatem Yousry


• inp = input("Enter the operation in the form operand operator operand: ")
• # If user wants to terminate
• # the server connection he can type Over
• if inp == "Over":
• break

Network Programming
# Here we send the user input
• # to server socket by send Method
• client.send(inp.encode())

• # Here we received output from the server socket


• answer = client.recv(1024)
• print("Answer is "+answer.decode())
• print("Type 'Over' to terminate")

• client.close() 55
Network Programming Dr. Hatem Yousry
56
Thank You

Dr. Hatem Yousry


Network Programming
Dr. Hatem Yousry
57
E-mail: [email protected]
Network Programming Dr. Hatem Yousry
58

You might also like