Users Online

· Guests Online: 148

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

What is Python Socket Programming (Basics)

What is Python Socket Programming (Basics)

Socket Programming

Python Socket Programming – Before I start with Python Socket Programming, I hope you have good basics in Python. If you also know Django, it would be even easier to understand. Nope, socket programming is unrelated to Django, but the terminologies in Python socket programming and Django are almost the same though they are two different categories. So to start with, what exactly is Python Socket Programming? Python Socket programming exists in Python, Java, and almost all other programming languages.

But in the case of Python, socket programming is elementary to understand. Python Socket programming means network programming. It includes client-side and Python Socket server-side related codes. But that definition is just as good as a book stating C programming is used to develop software. And Nah, I am not here for that. I am here to ensure you understand Python socket programming basics better before you start writing your own socket modules. So let us get started and see how the socket works either on the client side or on the Python Socket server side.

What is Python Socket Programming?

If you have learned C programming, then learning Python socket programming in Python would be easy since they are almost identical. To simplify it, python socket programming is just a piece of code about how computers in a network communicate. And this does not end with just a LAN-based network; it also supports WAN, MAN, and intranet-based networks. We even use sockets in our day-to-day life. Are we not understanding? Let me give you a simple example.

When you want to connect to, let’s, say, Facebook.com, you type the same thing in the URL bar. So, this connection you created is not just created by the DNS stuff. This is all configured through Python socket programming. Sockets decide how two networks communicate. Any communication going through a network may be a video, VOIP connection, or text; everything goes through a socket. Now that we know what sockets are, let us develop our socket in Python.

img11

Image source: pixabay.com

Types

Now there are loads of sockets out there. But we won’t be talking about all of them since I can’t cover every one of them here. You can create a UDP, TCP, or even a port socket; there are many more if I go on. But I would be looking more into TCP and UDP sockets today since they are the basics, and they can be perfect as a beginner point to get started with Python Socket programming.

UDP Sockets Programming

User Datagram Protocol, commonly known as UDP, is an alternative protocol to TCP that transfers packets from one host to another. But unlike TCP (transmission control protocol), UDP is a connectionless protocol, and it is non-stream oriented. This means the UDP server will only capture incoming packets from all the hosts without identifying a reliable source connection. We will use the socket. Socket function to do this. A simple UDP socket is created in the following manner in Python:

import socket              #importing socket module from python library#Now we need to create AF_INET and sock dgram sockets = socket. socket(socket.AF_INET, socket.SOCK_DGRAM)print “Socket Creation Successful.”

Yes. That’s it, and we have created a simple UDP socket here in Python. Python Socket Programming or even creating a simple socket is not rocket science. However, coding the UDP Server and the Client is a big deal. Since UDP sockets are connectionless, comms are initiated with send and receive socket functions. These functions don’t require them to connect. They can send and receive packets from any random source. Here is how a UDP Server is created:

import socket port = 2924s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.bind((“”, port))print “Requesting connectivity to the port on machine”, port
while 1:
data, address = s.recvfrom(1024)
print data

This may not seem much, but this is how it is created. One can use any port here. I have just chosen a random one as, 2924. The UDP server needs a port to be open to send and receive incoming connections. There is no listening to port or accepting connections or requests. It just happens without any authentication. Try running the above Server on a terminal and see how it works.

This is just a simple UDP Server that we have created. Let us make it a bit more exciting and also a bit more complicated:

'''This is a simple UDP socket server'''import socketimport sys
HOST = ""  # One can try all available interfaces here
PORT = 2924 # Any random port which is not used by default on Windows or Linux distros
# Coding the UDP Socket
try :
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print "Socket initialized"
except socket.error, msg :
print "Socket creation failed. Following error occured:" + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
# Now, we need to bind this socket to the above host and port
try:
s.bind((HOST, PORT))
except socket.error, msg:
print "Binding Socket failed. Following error interrupted the binding:" + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket binding completed.'
#Maintain the established connection
while 1:
# capture data from the client using variable data and address
d = s.recvfrom(1024)
data = d[0]
address = d[1]
if not data:
break
reply = 'OK...' + data
s.sendto(reply, address)
print 'Token message[' + address[0] + ':' + str(address[1]) + '] - ' + data.strip()
s.close()

Run the above program and start a UDP Server on port 2924. Congrats, you have successfully created a Socket in Python. And make sure you note that a UDP server can handle loads of clients, unlike the TCP server, because there is no fixed connectivity in a UDP server like in the case of a TCP server.

Recommended courses

  • UDP Client Programming

Now that we have successfully created a UDP Server, we need a client to establish a proper connection to it so that we know it’s working. So let us work on creating an appropriate UDP client in Python. This Client will connect to the UDP Server we created above:

”’Creating a Simple UDP client using sockets”’

import socketimport sys
# Creating a UDP Socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print 'Socket Creation failed'
sys.exit()
Host = '127.0.0.1'; #You can also try using localhost instead of this IP; both are the same.
port = 2924;
while(1) :
msg = raw_input('Type in a message to send to server: ')
try :
#Now, we need to set the strings
s.sendto(msg, (host, port))
# Now we need to recieve data and address from client using data and address
d = s.recvfrom(1024)
reply = d[0]
address = d[1]
print 'Reply from the server is:' + reply
except socket.error, msg:
print 'Following Error Appeared:' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()

Yup. Creating a UDP client in Python Socket programming is much easier than creating a UDP Server. But this is how it goes. I don’t think I need to explain anything from the above code since I have already mentioned all the required things in the # tag comments. Just ensure that the IP address and the port you have entered are proper and your firewall is not blocking the connection; otherwise, it will always fail no matter what.

TCP Socket Programming

Now that we have learned how to create a UDP client and Server let us look at programming TCP sockets. We will be using the same socket. Socket function to create a TCP socket here.

import socket  # Importing the module socket from python libraries#create an AF_INET and stream socketss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)print 'Socket Creation Successful'

AF_INET is used for Ipv4 address connection, and sock stream is a TCP-oriented protocol. This is a simple TCP socket that we have created. Now, we will be creating an advanced version of the same thing. We will also be throwing in exceptions here, as we pitched it when creating UDP Servers and Clients, so we will know where the actual program lies in case the connectivity fails. Socket. errors will be used to handle all of these errors, similar to UDP programming.

So now let’s create a socket with the above error handling and connect to the host facebook.com. This is how it needs to be done:

import socket #importing the socket moduleimport systry:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Socket Creation failed. Following error occured:' + str(msg[0]) + ', Error message : ' + msg[1]
sys.exit();
print 'Socket Creation successful.'
host = 'www.facebook.com'
port = 2924
try:
remote_ip = socket.gethostbyname( host )
except for socket.gaierror:
print 'Improper host name. Exiting...'
sys.exit()
print '' + host + IP address ' is ' + remote_ip
s.connect((remote_ip, port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip

Now, this is enough if we need to get a connection going. But that’s not our aim. We intend to create a connection to send and receive data on both ends. We can send data using the sendall function. So here is how it goes:

import socket #importing the socket moduleimport systry:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except for socket.error, msg:
print 'Socket Creation failed. Following error occured:' + str(msg[0]) + ', Error message : ' + msg[1]
sys.exit();
print 'Socket Creation successful.'
host = 'www.facebook.com'
port = 2924
try:
remote_ip = socket.gethostbyname( host )
except for socket.gaierror:
print 'Improper host name. Exiting...'
sys.exit()
print '' + host + IP address ' is ' + remote_ip
s.connect((remote_ip, port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
#transfering data using the sendall function
message = "GET / HTTP/1.1\r\n\r\n"
try :
s.sendall(message)
except socket.error:
#Send failed
print 'Transmission Failure'
sys.exit()
print 'Message Status: Sent.'

Now that we have created a successful connection, we can also send the data to see how we can receive the data altogether. This is how it goes:

import socket #importing the socket moduleimport systry:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except for socket.error, msg:
print 'Socket Creation failed. Following error occured:' + str(msg[0]) + ' , Error message : ' + msg[1]
sys.exit();
print 'Socket Creation successful.'
host = 'www.facebook.com'
port = 2924
try:
remote_ip = socket.gethostbyname( host )
except for socket.gaierror:
print 'Improper host name. Exiting...'
sys.exit()
print '' + host + IP address ' is ' + remote_ip
s.connect((remote_ip , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
#transfering data using the sendall function
message = "GET / HTTP/1.1\r\n\r\n"
try :
s.sendall(message)
except socket.error:
#Send failed
print 'Transmission Failure'
sys.exit()
print 'Message Status: Sent.'
#Now, in order to receive data, we use the recv function to achieve it
reply = s.recv(4096)
print reply

The final thing is we need to close the socket, which we could do by the following code:

s.close()

And finally, the binding part. We can use the function bind to bind together sockets with ip addresses and ports.

import socketimport sysHOST = '' #This is the same way we did in UDP protocolPORT = 2924 # port to access data.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket creation successful'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Binding failed. Following Error Occured' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket Binding successful.'

Now, we need to listen incoming for incoming connections if we need the Server to get connected. This can be done with the following simple command:

s.listen(10)print 'Listener started'

And finally, we need to create a socket to accept these connections:

import socketimport sysHOST = ''PORT = 2924
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket Creation successful'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Binding failed. Following error Occured' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket binding successful.'
s.listen(10)
print 'Listener started'
#Accepting connections
conn, addr = s.accept()
#Providing connected client info
print 'Connection established with ' + addr[0] + ':' + str(addr[1])

There is much more to this. We can also write codes for handlers and other stuff. But I think this would be it for now. Ensure you have these basics correct, after which the remaining parts are just a piece of cake to learn.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.82 seconds
10,811,863 unique visits