Socket programming in Python



Socket programming starts by importing a socket library and creating a simple socket.

 import socket s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) 

Here we made a socket instance and passed two parameters to it. The first parameter —  AF_INET, and the second —  SOCK_STREAM . AF_INET belongs to the ipv4 address family. SOCK_STREAM stands for connection oriented TCP.

We can now connect to the server using this socket.

Connecting to the server:
Please Note that if any error occurs during socket creation, socket.error is thrown and we can connect to the server only knowing that it is ip. You can find the IP address of the server using this:

 $ ping www.google.com 

You can also find the IP using Python:

 import socket ip = socket.gethostbyname (`www.google.com`) print ip 

Here is an example script to connect to Google

Output:

 Socket successfully created the socket has successfully connected to google on port == 173.194.40.19 
  • First of all we made an outlet.
  • Then we solved the IP address of Google and finally we connected to Google.
  • Now we need to know how we can send some data via socket.
  • The socket library has a sendall function to send data. This function allows you to send data to the server to which the socket is connected, and the server can also send data to the client using this function.

Simple server-client program:

Server:
The server has a bind () method that binds it to a specific ip and port so that it can listen for incoming requests to that ip and port. The server has a listen () method that puts the server into listening mode. This allows the server to listen for incoming connections. Finally, the server has accept () and close () methods. The accept method initiates a connection to the client, and the close method closes the connection to the client.

# Example script to connect to Google using a socket
# Python programming

import socket # for socket

import sys 

 

try :

s = socket.socket (socket.AF_INET, socket.SOCK _STREAM)

print "Socket successfully created "

except socket.error as err:

print "socket creation failed with error% s" % (err)

 
# default socket port

port = 80

 

try :

host_ip = socket.gethostbyname ( `www.google.com` )

except socket.gaierror:

 

# this means that failed to resolve host

print " there was an error resolving the host "

  sys.exit ()

 
# connect to server
s.connect ((host_ip, port))

 

print "the socket has successfully connected to google

on port = = % s "  % (host_ip)

# first of all import the socket library

import socket 

 
# then create a socket object

s = socket.socket () 

print "Socket successfully created"

 
# reserve a port on your computer in our
# happens 12345 but can be anything

port = 12345  

< code class = "undefined spaces">  
# Next port binding
# we didn`t enter ip in the ip field
# instead we entered an empty line
# this makes the server listen for requests
# coming from other computers on the network
s.bind ((``, port)) 

print "socket binded to% s" % (port)

 
# put socket in listening mode

s.listen ( 5

print "socket is listening"  

 
# forever th cycle until we interrupt it or
# an error occurs

while True :

 

# Contact customer.

c, addr = s.accept () 

print `Got connection from` , addr

 

  # send a thank you message to the client.

c.send ( ` Thank you for connecting` )

 

# Close client connection

c.close ()

  • First of all we import the socket we need.
  • Then we created a socket object and reserved a port on our computer.
  • After that we bind our server to the specified port. Passing an empty string means that the server can also listen for incoming connections from other computers. If we had passed 127.0.0.1, it would only listen to calls that were made on the local computer.
  • After that, we put the server into listening mode. 5 here means 5 connections are pending if the server is busy and if the 6th socket tries to establish a connection then the connection is rejected.
  • Finally, we do a while loop and start accepting all incoming connections and close these connections after a thank-you message to all connected sockets.

Client:
Now we need something the server can communicate with. We could send a request to the server to find out that our server is running. Enter these commands in a terminal:

 # start the server $ python server.py 

# keep the above terminal open
# Now open another terminal and type:

 $ telnet localhost 12345 

Output:

 # in the server.py terminal you will see # this output: Socket successfully created socket binded to 12345 socket is listening Got connection from (`127.0.0.1`, 52617) 
 # In the telnet terminal you will get this: Trying :: 1 ... Trying 127.0.0.1 ... Connected to localhost ... Escape character is `^]`. Thank you for connectingConnection closed by foreign host. 

This output shows that our server is running.

Now for the client side:

# Import a socket module

import socket 

 
# Create socket object

s = socket.socket () 

 
# Define the port you want to connect to

port = 12345  

 
# connect to server on local computer

s.connect (( `127.0 .0.1` , port))

 
# receive data from the server

print s.recv ( 1024 )

# close connection
s.close () 

  • First of all, we make a socket object.
  • Then we connect to the localhost on port 12345 (the port our server is running on) and finally get data from the server and close the connection.
  • Now save this file as client.py and run it from the terminal after running the server script.
 # start the server: $ python server.py Socket successfully created socket binded to 12345 socket is listening Got connection from (`127.0.0.1`, 52617) 
 # start the client: $ python client.py Thank you for c onnecting 

Link: Python Socket Programming

This article courtesy of Kishlai Verma . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please write in comments if you find anything wrong or if you`d like to share more information on the topic discussed above.