This article covers all areas dealing with Socket Programming in Python. Sockets help you make these connections, while Python, undoubtedly, makes it easy.
Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while other socket reaches out to the other to form a connection. Server forms the listener socket while client reaches out to the server.
They are the real backbones behind web browsing. In simpler terms there is a server and a client.
Socket programming is started by importing the socket library and making a simple socket.
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Here we made a socket instance and passed it two parameters. The first parameter is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address family ipv4. The SOCK_STREAM means connection oriented TCP protocol.
Now we can connect to a server using this socket.
Note that if any error occurs during the creation of a socket then a socket.error is thrown and we can only connect to a server by knowing it’s ip. You can find the ip of the server by 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 of a script for connecting to Google
# An example script to connect to Google using socket # programming in Python 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 port for socket port = 80 try: host_ip = socket.gethostbyname('www.google.com') except socket.gaierror: # this means could not resolve the host print "there was an error resolving the host" sys.exit() # connecting to the server s.connect((host_ip, port)) print "the socket has successfully connected to google \ on port == %s" %(host_ip)
Socket successfully created the socket has successfully connected to google on port == 22.214.171.124
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.A server has a listen() method which puts the server into listen mode. This allows the server to listen to incoming connections. 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.
# 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 12345 but it can be anything 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(5) 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('Thank you for connecting') # Close the connection with the client c.close()
Now we need something with which a server can interact. We could tenet to the server like this just to know that our server is working. Type these commands in the terminal:
# start the server $ python server.py
$ telnet localhost 12345
# 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 working.
Now for the client side:
# Import socket module 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()
# 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 connecting
In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.
Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).
Python is an interpreted, high-level, powerful general-purpose programming language. You may ask, Python’s a snake right? and Why is this programming language named after it?
Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, our full-stack Python development services...
Python any() function returns True if any element of an iterable is True otherwise any() function returns False. The syntax is any().