0% found this document useful (0 votes)
8 views21 pages

CPNT217 - 16. Socket Programming

Socket programming enables network-enabled applications to communicate over a network using sockets, which are software abstractions representing endpoints of connections. It involves creating, binding, listening, accepting connections, sending and receiving data, and closing sockets, with TCP and UDP being the two main protocols used. Best practices include proper error handling, resource management, and using encryption for security.

Uploaded by

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

CPNT217 - 16. Socket Programming

Socket programming enables network-enabled applications to communicate over a network using sockets, which are software abstractions representing endpoints of connections. It involves creating, binding, listening, accepting connections, sending and receiving data, and closing sockets, with TCP and UDP being the two main protocols used. Best practices include proper error handling, resource management, and using encryption for security.

Uploaded by

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

Socket

Programming
Introduction to socket programming
What is Socket
programming
Creating a basic socket
Why use sockets?
Socket Connection
The server receives the request on port 80 and sends a reply using port 80 as the new source. Note the reversal
of both the IP addresses and port numbers between the request and the reply.

IP Address Port
Source 112.156.54.89 9835
Destination 172.20.52.100 80

Internet

IP Address Port
Source 172.20.52.100 80
Destination 112.156.54.89 9835
Socket Programming – Background
Socket programming is a part of creating network-enabled applications that allow
different devices to communicate with each other over a network. In this type of
programming, developers use sockets to establish connections and transfer data
between devices.
A socket is a software abstraction that represents an endpoint of a network
connection. Each socket is associated with a unique IP address and port number,
which are used to identify the device and the specific application that is sending or
receiving data.
Socket programming involves two types of sockets: client sockets and server
sockets. Client sockets are used to initiate a connection with a server socket, while
server sockets listen for incoming connections from client sockets.
Socket Programming – Procedure
The process of socket programming involves the following steps:
• Creating a socket: In this step, developers create a socket object and specify
the protocol family, socket type, and protocol.
• Binding the socket: In this step, developers bind the socket to a specific IP
address and port number.
• Listening for incoming connections (for server sockets): Server sockets
enter a listening state and wait for incoming connections from client sockets.
• Accepting connections (for server sockets): When a client socket connects to
the server socket, the server socket accepts the connection and creates a new
socket object to handle the connection.
• Sending and receiving data: Once the connection is established, both the
client and server sockets can send and receive data through the socket.
• Closing the connection: When the communication is complete, the sockets
are closed to release the resources used by the connection.
More Socket Programming

• Socket programming is commonly used for building


various types of network-enabled applications such as
chat applications, file transfer applications, and web
servers. It is a low-level networking technology that
provides developers with a lot of control over how data
is transmitted and received over a network.
Why Use Sockets?
Sockets are widely used in network programming because they provide
a reliable, flexible, and efficient way for devices to communicate with
each other over a network. Here are some reasons why sockets are
commonly used:
• Platform independence: Sockets are available on most modern
operating systems, which makes it easy to write network applications
that can run on different platforms without modification.
• Protocol support: Sockets support a wide range of protocols, including
TCP/IP, UDP, and HTTP, which makes them suitable for building various
types of network applications.
• Flexibility: Sockets provide developers with a lot of control over how
data is transmitted and received over a network, allowing them to fine-
tune their applications for performance and reliability.
Why Use Sockets?, cont.
• Scalability: Sockets can allow applications to handle multiple
connections simultaneously, which makes them ideal for
building high-performance server applications.
• Security: Sockets can be used with encryption protocols such
as SSL/TLS to provide secure communication over a network.
• Efficiency: Sockets use low-level network protocols to
minimize overhead and maximize performance, making them
suitable for applications that require high-speed data transfer.
Overall, sockets provide a robust and versatile programming
interface for building network applications that require reliable
and efficient communication between devices.
Types of Sockets in
Python
TCP vs. UDP
TCP stands for Transmission Control Protocol, which is UDP stands for User Datagram Protocol, which is a
a connection-oriented and reliable transport protocol connectionless and unreliable transport protocol used
used for transmitting data over a network. TCP for sending datagrams (packets) over a network. UDP
provides features such as data segmentation, flow is a simple protocol that does not guarantee the
control, error checking, and retransmission of lost delivery or order of packets, nor does it establish a
packets, making it a suitable choice for applications dedicated connection between the sender and
that require reliable and ordered delivery of data. receiver.
To create a TCP socket in Python, you can use the To create a UDP socket in Python, you can use the
socket module and the SOCK_STREAM parameter to socket module and the SOCK_DGRAM parameter to
indicate that you want to use the TCP protocol. indicate that you want to use the UDP protocol.

• Some of the key differences between UDP and TCP include:


• Reliability: TCP provides reliable, ordered, and error-checked delivery of data, while UDP does not.
• Connection-oriented vs. connectionless: TCP is a connection-oriented protocol, which means it
establishes a dedicated connection between the sender and receiver before transmitting data.
UDP, on the other hand, is a connectionless protocol that does not establish a dedicated
connection.
• Flow control and congestion control: TCP includes flow control and congestion control mechanisms
to manage the rate of data transmission and avoid network congestion. UDP does not include
these mechanisms.
Types of Sockets in Python
In Python, there are two types of sockets that can be used for network
programming:
• TCP Sockets: TCP (Transmission Control Protocol) sockets provide reliable, ordered,
and error-checked delivery of data between devices over a network. They are
connection-oriented, which means that a connection must be established between
the client and server before data can be transferred. TCP sockets are ideal for
applications that require reliable data transfer, such as file transfer applications,
email clients, and web browsers.
• UDP Sockets: UDP (User Datagram Protocol) sockets provide fast and unreliable
delivery of data between devices over a network. They are connectionless, which
means that data can be sent without establishing a connection first. UDP sockets
are ideal for applications that require fast data transfer, such as real-time video
streaming and online gaming.
In Python, both TCP and UDP sockets can be created using the built-in socket
module. The socket module provides a simple and consistent interface for creating
and using sockets, regardless of the underlying network protocol.
Creating Sockets – Explained
• To create a TCP socket in Python, you can use the following code:
• import socket
• # create a TCP socket
• tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
• To create a UDP socket in Python, you can use the following code:
• import socket
• # create a UDP socket
• udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

In both cases, the first argument to the socket() function specifies the protocol family (in this case,
AF_INET for IPv4) and the second argument specifies the socket type (in this case, SOCK_STREAM for
TCP and SOCK_DGRAM for UDP).
Setting up a Socket
Server
Create a socket server

• Creating your socket server • What this server does:


import socket • This server listens for incoming
IP_ADDRESS = '127.0.0.1' connections on port 8000 and
PORT = 8000
server_socket = socket.socket(socket.AF_INET,
sends back any data received
socket.SOCK_STREAM) from the client. Note that this
server_socket.bind((IP_ADDRESS, PORT))
code only handles a single
server_socket.listen()
print('Server listening on port', PORT) client connection. If you want to
client_socket, client_address = handle multiple client
server_socket.accept()
print('Client connected:', client_address)
connections, you will need to
data = client_socket.recv(1024) use threads or asynchronous
print('Received data:', data.decode()) programming.
client_socket.sendall(data)
print('Data sent back to client')
client_socket.close()
server_socket.close()
Binding your Socket
When setting up a socket server in Python, you need to bind it to a
specific IP address and port so that clients can connect to it. The IP
address specifies which network interface to use, and the port
number identifies the specific service on that interface.

You can bind a socket server to an IP address and port using the bind()
method of the socket object. The bind() method takes a tuple
argument that specifies the IP address and port number to bind to.
The IP address can be a string representing a hostname or an IP
address in dotted-quad notation.
Moving Data
• To send and receive data with
sockets in Python, you can
use the send() and recv()
methods of the socket object.
The send() method is used to
send data over the socket,
while the recv() method is
used to receive data from the
socket.
Secure Socket Layer (SSL)
• SSL (Secure Sockets Layer) is a protocol that provides secure communication
over a network. It is commonly used for securing web traffic (HTTPS) but can
also be used for other types of network communication, including socket
programming.
• Some advantages of using SSL include:
• Encryption: SSL uses encryption to protect the confidentiality of data transmitted
over a network, making it difficult for attackers to intercept and read the data.
• Authentication: SSL provides mechanisms for verifying the identities of the
communicating parties, helping to prevent impersonation and man-in-the-middle
attacks.
• Integrity: SSL includes mechanisms for detecting and preventing tampering with
the data being transmitted over the network, ensuring its integrity.
• To create an SSL socket in Python, you can use the ssl module in combination
with the socket module

Note: SSL has been superseded by Transport Layer Security (TLS), which offers better encryption and more security features.
WebSockets
• WebSockets is a method for bidirectional communication between a
client and a server over a network. Unlike regular HTTP connections,
which are request-response based, WebSockets enables ongoing, real-
time communication between the client and server.

• WebSockets works by establishing a persistent connection between


the client and server, allowing them to send messages to each other in
real-time. Once the WebSocket connection is established, either the
client or server can send messages at any time, without the need for
an explicit request or response.

• To create a WebSocket server in Python, you can use the websockets


module.
Best Practices
• Socket programming in Python can be challenging, especially when it comes to
debugging, error handling, and security. Here are some best practices to keep in
mind when working with sockets:
• Error handling: Sockets can raise a wide range of errors, such as connection errors, timeout
errors, and protocol errors. It's important to handle these errors properly to prevent crashes
and ensure that your program behaves correctly. Use try-except blocks to catch exceptions and
handle them appropriately, such as logging the error or retrying the operation.
• Closing sockets properly: Always remember to close your sockets properly to prevent
resource leaks and ensure that the socket is released for other applications to use. Use the
close() method to close your sockets when you're done using them.
• Avoiding security risks: Socket programming can be vulnerable to security risks such as
buffer overflows, injection attacks, and man-in-the-middle attacks. To avoid these risks, always
validate user input, use encryption (such as TLS/SSL) for sensitive data, and implement
authentication and authorization mechanisms where possible.
• Debugging techniques: When debugging socket programs, it can be helpful to use logging to
trace the flow of data and identify issues. You can use tools such as Wireshark to capture and
analyze network traffic and use print statements to output debug information at strategic
points in your code.
• Use context managers: To ensure proper resource management, use context managers to
handle sockets. Context managers can help manage the opening and closing of sockets in a
clean and concise way.
Summary
• Socket programming is a powerful and important aspect of network programming. In
Python, you can use the socket module to create and manage sockets for
communicating over the network.
• Some key points to remember when working with sockets in Python include:
• Sockets can be used with different protocols, such as TCP, UDP, and SSL.
• When creating a socket server, you need to bind the socket to an IP address and port.
• You can use the send() and recv() methods to send and receive data over a socket.
• Always handle errors properly and close sockets when you're done using them to prevent
resource leaks.
• Use TLS/SSL to encrypt sensitive data and avoid security risks.

Here are some additional resources for learning socket programming with Python:
• Python documentation on socket programming: https://docs.python.org/3/library/socket.html
• Real Python's Socket Programming in Python (Guide): https://realpython.com/python-sockets/
• Socket Programming HOWTO (Python 3): https://docs.python.org/3/howto/sockets.html
• Socket Programming in Python (GeeksforGeeks): https://www.geeksforgeeks.org/socket-
programming-python/
• Introduction to Network Programming with Python (Udacity):
https://www.udacity.com/course/introduction-to-networking--ud436

You might also like