NWProg S23
NWProg S23
Hatem Yousry
Network Programming
Network Programming 1
Dr. Hatem Yousry
Agenda
• Addressing,
• Handling IPv4 addresses.
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
Network Programming
• Network programming is the discipline of designing and
implementing network programs.
3
The Key Players
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
Network Programming
• Conversation in proper order
• Understand each other
5
Networking Address
• Machines have a hostname and IP address
• Programs/services have port numbers
Network Programming
6
Internet Addresses
• The current IPv4 addresses ( 32 bit ) is about to
running out.
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
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.
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)
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
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
23
Python Socket Support
• Python supports socket networking through the socket module.
• The module provides the Berkeley Software Distribution (BSD)
socket interface.
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
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.
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
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)
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,
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
.
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()
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.
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
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.
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
Network Programming
• # now open another terminal and type:
• telnet localhost 12345
37
A Simple Client
• # Import socket module
• import socket
Network Programming
• # connect to the server on local computer
• s.connect(('127.0.0.1', port))
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.
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
Network Programming
tasks/applications.
41
Python Internet modules
• A list of some important modules in Python Network/Internet
programming.
Network Programming
FTP File transfers 20 ftplib, urllib
43
Multi Server Simulator
Create Virtual Test Networks
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
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
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
Network Programming
47
Server - msg
• import socket
• s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
• s.bind((socket.gethostname(), 1234))
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,
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
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
•
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()
Network Programming
print("Equation is received")
• result = 0
• operation_list = msg.split()
• oprnd1 = operation_list[0]
• operation = operation_list[1]
• oprnd2 = operation_list[2]
Network Programming
elif operation == "*":
• result = num1 * num2
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
Network Programming
# Here we send the user input
• # to server socket by send Method
• client.send(inp.encode())
• client.close() 55
Network Programming Dr. Hatem Yousry
56
Thank You