Skip to main content

Socket Programming

SOCKET PROGRAMMING TCP


Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.
Python also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.
What is Sockets?
Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents.
Sockets may be implemented over a number of different 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.
Sockets have their own vocabulary −

Term & Description
1Domain The family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
2type The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
3protocol Typically zero, this may be used to identify a variant of a protocol within a domain and type.
4hostname 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 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.
5port 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)
Here is the description of the parameters −
  • socket_family − This is either AF_UNIX or AF_INET, as explained earlier.
  • 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. Following is the list of functions required −
Server Socket Methods

Method & Description
1s.bind() This method binds address (hostname, port number pair) to socket.
2s.listen() This method sets up and start TCP listener.
3s.accept() This passively accept TCP client connection, waiting until connection arrives (blocking).
Client Socket Methods

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

Method & Description
1s.recv() This method receives TCP message
2s.send() This method transmits TCP message
3s.recvfrom() This method receives UDP message
4s.sendto() This method transmits UDP message
5s.close() This method closes socket
6socket.gethostname() Returns the hostname.
A Simple Server
To write Internet servers, we use the socket function available in socket module to create a socket object. A socket object is then used to call other functions to setup a socket server.
Now call bind(hostname, port) function to specify a port for your service on the given host.
Next, call the accept method of the returned object. This method waits until a client connects to the port you specified, and then returns a connection object that represents the connection to that client.
#!/usr/bin/python          #server.py file
import socket               # Import socket module
s = socket.socket()       # Create a socket object
host = socket.gethostname()      # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))       # Bind to the port
s.listen(5)                     # Now wait for client connection.
while True:
   c, addr = s.accept()              # Establish connection with client.
   print (‘Got connection from’, addr)
   c.send(‘Thank you for connecting’)
   c.close()                    # Close the connection
A Simple Client
Let us write a very simple client program which opens a connection to a given port 12345 and given host. This is very simple to create a socket client using Python’s socket module function.
The socket.connect (hosname, port ) opens a TCP connection to hostnameon the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file.
The following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits −
#!/usr/bin/python           # This is client.py file
import socket                 # Import socket module
s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                  # Reserve a port for your service.
s.connect((host, port))
print (s.recv(1024))
s.close()                           # Close the socket when done
Now run this server.py in background and then run above client.py to see the result.
# Following would start a server in background.
$ python server.py & 
# Once server is started run client as follows:
$ python client.py
This would produce following result −
Got connection from (‘127.0.0.1’, 48437)
Thank you for connecting

Comments

Popular posts from this blog

Generate Traffic in Simulation Mode

Objectives Part 1: Generate Network Traffic in Simulation Mode Part 2: Examine the Functionality of the TCP and UDP Protocols Background This simulation activity is intended to provide a foundation for understanding the TCP and UDP in detail. Simulation mode provides the ability to view the functionality of the different protocols. As data moves through the network, it is broken down into smaller pieces and identified in some fashion so that the pieces can be put back together. Each of these pieces is assigned a specific name (protocol data unit [PDU]) and associated with a specific layer. Packet Tracer Simulation mode enables the user to view each of the protocols and the associated PDU. The steps outlined below lead the user through the process of requesting services using various applications available on a client PC.  This activity provides an opportunity to explore the functionality of the TCP and UDP protocols, multiplexing and the function of port numbers in ...

Configuring Open Shortest Path First (OSPF) Protocol

Open Shortest Path First (OSPF) Protocol OSPF is a  Link State protocol   that’s considered may be the most famous protocol among the Interior Gateway Protocol (IGP) family, developed in the mid 1980’s by the OSPF working group of the IETF. When configured, OSPF will listen to neighbors and gather all link state data available to build a topology map of all available paths in its network and then save the information in its topology  database, also known as its  Link-State Database  ( LSDB ). Using the information from its topology database. From the information gathered, it will calculate the best shortest path to each reachable subnet/network using an algorithm called  Shortest Path First  ( SFP ) that was developed by the computer scientist  Edsger W. Dijkstra  in 1956. OSPF will then construct  three tables  to store the following information: Neighbor Table:  Contains all discovered OSPF neighbors  with whom r...