Socket Programming
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 the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. They are the real backbones behind web browsing. In simpler terms, there is a server and a client. We can use the socket module for socket programming. For this, we have to include the socket module –
import socket
to create a socket we have to use the socket.socket() method.
Syntax:
socket.socket(socket_family, socket_type, protocol=0)
Where,
- socket_family: Either AF_UNIX or AF_INET
- socket_type: Either SOCK_STREAM or SOCK_DGRAM.
- protocol: Usually left out, defaulting to 0.
Example:
Python3
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print (s) |
Output:
<socket.socket fd=74, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(‘0.0.0.0’, 0)>
The socket module provides various methods for both client and server-side programming. Let’s see each method in detail.
Python Network Programming
Python provides two levels of access to network programming. These are –
- Low-Level Access: At the low level, you can access the basic socket support of the operating system. You can implement client and server for both connection-oriented and connectionless protocols.
- High-Level Access: At the high level allows to implement protocols like HTTP, FTP, etc.
In this article, we will discuss Network Socket Programming. But before getting started let’s understand what are sockets.