Python AF_INET Socket

“A network may be set up such that two nodes can interact with one another using socket programming. Whereas the other socket reaches out to another to link, one socket (node) listening on a certain port upon an IP address. During the client’s connection to the server, the server creates the listener socket. They form the basis of online browsing. The very first step in socket programming is incorporating the socket package and generating a simple socket.

AF_INET is the very first argument, while SOCK_STREAM would be the next. AF_INET represents the ipv4 address family. In contrast to ipv6 to AF INET6, AF INET refers to the branch or realm. The connection-oriented TCP communication is referred to as SOCK_STREAM. Within this article, we will be taking a look at the use of the AF_INET parameter in socket programming of Python within the Spyder tool.”

Example 1

We have been getting started with the very first example of this article to create a secure connection between the socket and the host server. For this, we have been importing the socket module of python in the first line and the “sys” module in the second line using the “import” keyword. After that, we have been utilizing the concept of exception handling by using the try-except statement of python two times in this code.

Firstly, the try statement has been creating a new socket “s” using the “socket” function of a socket module in python with its two parameters, AF_INET and SOCK_STREAM. The AF_INET shows that the socket will be using the ipv4 family, and the SOCK_STR EAM has been used to utilize the TCP protocol for the connection stream. The print function has been using the simple sentence to print out at the console of the Spyder tool to display that the socket creation has been accomplished.

If the attempt to get the IP address is successful, the statement’s unless clause is skipped, and the remaining code is executed accordingly. The except statement has been used to display the error at the console if the creation of a socket got unsuccessfully used the socket.error object and saving it to variable “e”. After the try-except() statement, we have been initializing the port number “p” to 80 for the socket, i.e., the default port of socket connection to a web server is 80. The very next step is to resolve the host and connect the socket with it using the host ip address.

For this, we have been utilizing the “try-except” statement once again in the python code. The try statement has been started with the use of the gethostbyname() function of the socket module, which has been using the URL of Google to get its “IP” and save it to the hip variable. If the ip address has been found successfully, it will not execute the except statement and continue executing the next lines of code. Otherwise, if the except statement got the “gaierror” of the socket module, it will use the print statement to display that we are unable to resolve the ip of a host, and the “sys” module will be used to call its “exit()” function to terminate the program right at the moment.

After both try-except statements, we have been using the just got ip address as “hip” and the port number “p” to connect the socket with the Google host, i.e., using the connect() function of the socket module. The final line’s print statement will show that the socket has connected properly to the Google Host. Let’s save and run our code in the Spyder to see what we have got in return.

import socket

import sys


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

print("Accomplished the Socket Creation!")

except socket.error as e:

print("Failed to create socket , ERROR: %s" %(e))

p = 80


hip = socket.gethostbyname('')

except socket.gaierror:

print("Got Error while resolving the Host!")


s.connect((hip, p))

print("Socket has been Successfully Linked to Google...!")

After running it, we got the success messages on our Spyder console screen. The first message has been showing that the socket was created perfectly, and the second line has been showing that the connection was also established.

Example 02

A communication system called UDP sends individual packets through the web without assurances of timely delivery or guaranteed arrival. The Quotation of the Day is such a service that employs UDP (QOTD). We have started this program with the import of the socket module. After that, we have been using the context manager “with” to create a new socket as “soc” utilizing the AF_INET and SOCK_DGRAM parameters in the socket() function of the socket module to create a DATAGRAM socket of the ipv4 family.

After this, we have been using the variable “text” to initialize an empty message. The QOTD service operates by passing random information to the socket; when we deliver a blank message, it just answers with a quotation. We employ binary sequences for TCP/UDP communications. The port number has been set to 17 to receive quotation data. We have been using the URL of a host and the port number to get the ip address “adr” of the particular host. This “adr” address and the empty message “text” has been passed to the sendto() function of the socket module with the “soc” object to send it to the particular host.

The “recvfrom” function is the method used by UDP sockets to retrieve information. The buffer size serves as its parameter. The returned response is a duo (data, address), in which the “address” parameter is the identifier of the socket that delivered the data, and the “info” parameter is a byte sequence containing the data that was obtained. The print statement has been using the “decode” function to decode and display the information we have got.

import socket

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as soc:

text = b''

p = 17

adr = ("", p)

soc.sendto(text, adr)

info, address = soc.recvfrom(1024)


When we execute this program, we have got the quotation in return.


This article is all about the use of the AF_INET family of socket modules in python. We have tried two examples to create a socket, connect it to the host, send an empty message, and receive the quotations from the host.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content