Loading, please wait...

A to Z Full Forms and Acronyms

Socket Programming in Python | Python Tutorials

This article is all about socket programming with example.

What is Socket Programming in Python?

Socket programming is a way of connecting two nodes on a network to communicate with each other. One node(socket) listens on a particular Port at an IP and another node(socket) reaches out to it. The Server is a listener Socket and the client reaches out to the server. In simple terms, these are nothing but a Server and Client. Sockets are the real backbones behind web browsing.

Now, let’s start the socket programming, socket programming in python is started by importing the “socket” library.

Code:

import socket

sckt  = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Here “sckt”  is a socket instance and we have passed it two parameters socket.AF_INET and socket.SOCK_STREAM. AF_INET refers to the address-family ipv4. The SOCK_STREAM means connection-oriented TCP protocol.

Now using this socket instance ‘sckt’ we can connect to any server. So now, we will see how we can connect to a server.

Connecting to a server :

 If we know the IP address of any server then only we can connect to it. But if any error occurs during the establishment of connection or creation of a socket then an error called “socket.error” is thrown. Now let’s see how we can find the IP address of any server.

We can easily get the ip address of any server by using gethostbyname() function.

ipadress= socket.gethostbyname(‘www.tutorialslink.com’)

Now let’s see a script to connect to www.tutorialslink.com

Code:

# connect to Tutorialslink using socket programming in Python 
#importing socket package
import socket
#importing sys package
import sys 

try:
    #instance of socket 
	sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
	print("Socket created sucessfully")
except socket.error as err: 
	print("socket creation failed with error %s" %(err)) 

# default port for socket 
port = 80

try: 
    #get the IP address by gethostbyname() function
	host_ip = socket.gethostbyname('www.tutorialslink.com') 
except socket.gaierror: 

	# this means could not resolve the host 
	print("error occured during resolving the host")
    #exit the system
	sys.exit() 

# connecting to the server  
sckt.connect((host_ip, port)) 
#printing the msg with ip address
print("the socket has successfully connected to tutorialslink \n on port == %s" %(host_ip)) 

Now, we will see a server-client program to understand socket programming.

Server:

The server has many methods, we will discuss only these which we will use in our code.

  1. bind(): It helps to bind the port to a specific IP address, to listen to the incoming request on that port and IP.
  2. listen(): this method listens to the request of an incoming connection. i.e it puts the server in listening mode.
  3. accept(): this accepts or initiates a connection with the client.
  4. close(): this terminates the connection with the client.

Code:

  • First, we Import the socket library.
  • Make a socket instance and reserve a port on our system.
  • Bind the server with the specified port.
  • Now using listen method put the server into listening mode. 6 here means if the server is busy then wait till the 6 connections, after this the connection will be refused.
  • While the loop is used to accept all the incoming connections and close the connection.
#Import the socket library 
import socket			 

#create a socket object 
s = socket.socket()		 
print("Socket successfully created")

# reserve a port on your computer 
port = 12345				

# Next bind to the port 
# we have not typed any ip in the ip field 
# instead we have inputted an empty string 
# this makes 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(6)	 
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('Thanks for connecting') 

# Close the connection with the client 
c.close() 

 Client:

 Till now, we have created a server, now we need some clients so that server can interact with it.

  • First, import the module and create a socket instance.
  • Connect to localhost
  • Write code to receive the data
  • Close the connection.

Code:

#Importing socket package 
import socket                
  
# Create a socket object 
s = socket.socket()          
  
# Define the port on which you want to connect 
port = 12345                
  
# 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() 

Output: 

1. run server.py first on terminal & keep it running. 

2. Now open a new terminal and run client.py 

Hope you got how we can create a socket and connect to any server using that socket. So now we will write a python code to get the IP address of the current system on which python interpreter is running.

Let’s see the code for the same.

Code:

#importing socket module: this module provides access to BSD socket interface
import socket

#defining a function to get the Hostname and IP
def getHostname_IP():
    # try block
    try:
        #socket.gethostname() function returns the host name of the system 
        # under which python interpreter is running
        hostname= socket.gethostname()
        #socket.gethostbyname() to get the IP address of the local host.
        hostip=socket.gethostbyname(hostname)
        #print hostname
        print("Hostname : ",hostname)
        #print hostip
        print("Host IP : ", hostip)
    #if connection between two nodes doesn't establish then you will reach this block.
    except:
        #print Exception
        print("Sorry.....Unable to get the hostname an IP")    

#call the function
getHostname_IP()        

output:

Thanks, for reading this article, stay tuned with us for more articles and keep learning.

A to Z Full Forms and Acronyms

Related Article