Python network programming examples Tutorial: The python programming language has libraries that provide higher-level access to specific application-level network protocols like FTP, HTTP, etc.
The python programming will provide two levels of access to network services.
Then we access the basic socket support in the operating system that allows you to implement clients and servers.
Here server and client both connection-oriented and connectionless protocols.
Sockets:-
They are endpoints of a bidirectional communications channel.
Also communicate within a process between the same machine, and different continents.
The sockets may be implemented several different channel types as,
UNIX domain sockets,
TCP, UDP.
The socket library will provide a specific class for handling common transports as well as a generic interface.
Methods are as follows,
Sr.No. |
Term & Description |
1 |
Domain:-is the family of the protocol used as a transport mechanism. |
2 |
Type:-is communication between two endpoints for connection-oriented protocols and SOCK_DGRAM for the connectionless protocols. |
3 |
Protocol:-used to identify the variant of protocol within a domain and type. |
4 |
Hostname:-the dotted-quad address or an IPv6 in the colon. |
You need to use socket.socket () function to create the socket.
The syntax is:-
s = socket. socket (socket_family, socket_type, protocol=0)
The parameters are,
The server socket methods are,
We will use the socket function to create a socket object used to call other functions to set up a socket server.
We have to call bind function to specify a port of service on the given host.
Then accept method of the returned object the method waits until a client connects to the port.
import socket
s = socket. socket ()
host = socket.gethostname ()
port = 12345
s.bind ((host, port))
s.listen (5)
while True:
c, addr=s.accept ()
Print’Got connection from’, addr
c.send (‘Thank you for connecting’)
c.close ()
The socket.connect will open a TCP connection to the hostname on the port.
After opening socket, you can read it like any IO objects.
import socket
s=socket. socket ()
host=socket.gethostname ()
port=12345
s.connect ((host, port))
print s.recv (1024)
s.close ()
Run the server.py as,
$python server.py&
$python client.py
Got connection from ('127.0.0.1', 48437)
Thank you for connecting
Protocol |
Common function |
Port No |
Python module |
HTTP |
Web pages |
80 |
httplib, urllib, xmlrpclib |
SMTP |
Sending email |
25 |
smtplib |
POP3 |
Fetching email |
110 |
poplib |
IMAP4 |
Fetching email |
143 |
imaplib |
Telnet |
Command lines |
23 |
telnetlib |
Gopher |
Document transfers |
70 |
gopherlib, urllib |
NNTP |
Usenet news |
119 |
nntplib |
FTP |
File transfers |
20 |
ftplib, urllib |