close

Python Network Programming – What is Socket Programming in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Python Socket Programming

In this Python tutorial, we are going to study Python Network Programming. With Python, we can access an operating system’s socket support. This will let you implement clients and servers for connection-oriented and connectionless protocols. Moreover, this Python 3 tutorial gave you an understanding of Socket programming in Python with vocabulary and examples. Along with this, we will learn the Python socket Module and Python socket Methods.

So, let’s begin networking in Python 3.

Python 3 Network Programming

Python 3 Network Programming

Introduction to Python Network Programming

In Python, there are 2 levels of networking programs:

  • Low- level access: Here, you can access the basic socket support of an operating system.
  • High- level access: Protocols such as HTTPS, FTP, etc. can be implemented at a higher level.

To learn Python Network Programming, first begin with Python Socket Programming.

Consider a bidirectional communication channel. Its end-points are what we call sockets. Sockets may communicate in one of the following ways:

  1. Within a process
  2. Between processes on the same machine
  3. Between processes on different machines

Learn Python Closure – Nested Functions and Nonlocal Variables

Python Socket Vocabulary

Let’s take a look at all we talk about when we talk about sockets.

Python 3 Network Programming

Python 3 Network Programming- Python Socket vocabulary

a. Domain

For transport, we use protocols like AF_INET, PF_INET, PF_UNIX, and PF_X25, among others. This family of protocols is the domain.

b. Type

Communication between two endpoints may typically be of type SOCK_DGRAM for connectionless protocols and SOC_STREAM for connection-oriented ones.

c. Protocol

This identifies the protocol used within a domain and type. This is typically zero.

d. Port

Servers listen to one or more ports for client calls. But what values can a port take? A Fixnum port number, a service name, or a string holding the port number.

e. Hostname

A hostname is what identifies a network interface. This can be a string holding a hostname, a dotted-quad address, or an IPv6 address. This can also be a zero-length string, an Integer, or a string “<broadcast>”.
We can implement a socket over different channel types- like TCP and UDP. We can also use the socket library to handle transport.
Read Python Modules Vs Packages

Python Socket Module

Let’s first import the Python socket module for this.

>>> import socket
>>>

Now, we can use the socket.socket(socket_family,socket_type,protocol=0) function to create a socket.

>>> mysocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> mysocket

<socket.socket fd=1524, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0>

Here, socket_family may take one of the values AF_UNIX and AF_INET. socket_type may be SOCK_STREAM or SOCK_DGRAM. protocol defaults to zero.

Python Socket Methods

Now, we may call any of these methods on this object we just created.

Python Network Programming

Python Network Programming- Python Socket Methods

a. Server Socket Methods in Python

i. s.bind() method in Python

This binds the address to the socket. This address holds the hostname and the port number pair.

ii. s.listen() method in Python

This starts the TCP listener.

iii. s.accept() method in Python

This method passively accepts the TCP client connection and blocks until the connection arrives.

b. Client socket methods in Python

i. s.connect() methods in Python

This actively initiates a TCP server connection.
And 

c. General socket methods in Python

i. s.send() methods in Python

This sends the TCP message.

ii. s.sendto() methods in Python

This sends the UDP message.

iii. s.recv() methods in Python

This receives the TCP message.

iv. s.recvfrom() methods in Python

This receives the UDP message.

v. s.close() methods in Python

This method closes the socket.

vi. socket.gethostname() methods in Python

This returns the hostname.

a. Examples-Server

Let’s first try implementing a simple server.

>>> import socket
>>> myserver=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> host=socket.gethostname()
>>> port=9999
>>> myserver.bind((host,port))
>>> myserver.listen(5)  #This asks for permission on Windows
>>> while True:
      myclient,addr=myserver.accept()
      print(f"Connected to {str(addr)}")
      myclient.send(msg.encode("ascii"))
      myclient.close()

b. Examples-Client

Now, let’s try implementing a client.

>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> host=socket.gethostname()
>>> port=9999
>>> s.connect((host,port))
>>> msg=s.recv(1024)
>>> s.close()
>>> print(msg.decode("ascii"))

Other Internet Modules

There are some other modules. Now, let us work with networks:

  1. httplib, urllib, xmlrpclib- For the HTTP protocol, dealing with web pages, on port 80.
  2. nntplib- For protocol NNTP, dealing with Usenet news, on port 119.
  3. ftplib, urllib– For protocol FTP, dealing with file transfers, on port 20.
  4. smtplib– For protocol SMTP, dealing with sending email, on port 25.
  5. poplib- For protocol POP3, for fetching email, on port 110.
  6. imaplib- For protocol IMAP4, for fetching email, on port 143.
  7. telnetlib- For the protocol Telnet, for dealing with command lines, on port 23.
  8. gopherlib, urllib– For protocol Gopher, for dealing with document transfers, on port 70.

Exceptions Thrown by Socket Programming in Python

The socket module may throw one of the following exceptions:

a. exception socket.error in Python

This represents a socket-related error.

b. exception socket.herror in Python

This represents an address-related error.

c. exception socket.gaierror in Python

This represents an address-related error.

d. exception socket.timeout in Python

This occurs when a socket times out.

So, this was all about Python Network Programming in today’s Python Tutorial. Hope you like our explanation.

Conclusion

Hence, we discussed the basics of Python Network programming. Basically, an introduction to Python Socket Programming and Python Socket Vocabulary. Moreover, we discussed the Socket Module and Socket methods with the help of examples. Lastly, we saw other internet Modules and Exceptions thrown by Python Socket. Furthermore, if you have any queries, feel free to ask in the comments section. 
For reference

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

courses
Image

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

Leave a Reply

Your email address will not be published. Required fields are marked *