English 中文(简体)
Python 3 - Networking
  • 时间:2024-12-22

Python 3 - Network Programming


Previous Page Next Page  

Python provides two levels of access to the network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement cpents and servers for both connection-oriented and connectionless protocols.

Python also has pbraries that provide higher-level access to specific apppcation-level network protocols, such as FTP, HTTP, and so on.

This chapter gives you an understanding on the most famous concept in Networking - Socket Programming.

What is Sockets?

Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents.

Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. The socket pbrary provides specific classes for handpng the common transports as well as a generic interface for handpng the rest.

Sockets have their own vocabulary −

Sr.No. Term & Description
1

domain

The family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.

2

type

The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.

3

protocol

Typically zero, this may be used to identify a variant of a protocol within a domain and type.

4

hostname

The identifier of a network interface −

    A string, which can be a host name, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation

    A string "<broadcast>", which specifies an INADDR_BROADCAST address.

    A zero-length string, which specifies INADDR_ANY, or

    An Integer, interpreted as a binary address in host byte order.

5

port

Each server pstens for cpents calpng on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.

The socket Module

To create a socket, you must use the socket.socket() function available in the socket module, which has the general syntax −

s = socket.socket (socket_family, socket_type, protocol = 0)

Here is the description of the parameters −

    socket_family − This is either AF_UNIX or AF_INET, as explained earper.

    socket_type − This is either SOCK_STREAM or SOCK_DGRAM.

    protocol − This is usually left out, defaulting to 0.

Once you have socket object, then you can use the required functions to create your cpent or server program. Following is the pst of functions required −

Server Socket Methods

Sr.No. Method & Description
1

s.bind()

This method binds address (hostname, port number pair) to socket.

2

s.psten()

This method sets up and start TCP pstener.

3

s.accept()

This passively accept TCP cpent connection, waiting until connection arrives (blocking).

Cpent Socket Methods

Sr.No. Method & Description
1

s.connect()

This method actively initiates TCP server connection.

General Socket Methods

Sr.No. Method & Description
1

s.recv()

This method receives TCP message

2

s.send()

This method transmits TCP message

3

s.recvfrom()

This method receives UDP message

4

s.sendto()

This method transmits UDP message

5

s.close()

This method closes socket

6

socket.gethostname()

Returns the hostname.

A Simple Server

To write Internet servers, we use the socket function available in socket module to create a socket object. A socket object is then used to call other functions to setup a socket server.

Now call the bind(hostname, port) function to specify a port for your service on the given host.

Next, call the accept method of the returned object. This method waits until a cpent connects to the port you specified, and then returns a connection object that represents the connection to that cpent.

#!/usr/bin/python3           # This is server.py file
import socket                                         

# create a socket object
serversocket = socket.socket(
	        socket.AF_INET, socket.SOCK_STREAM) 

# get local machine name
host = socket.gethostname()                           

port = 9999                                           

# bind to the port
serversocket.bind((host, port))                                  

# queue up to 5 requests
serversocket.psten(5)                                           

while True:
   # estabpsh a connection
   cpentsocket,addr = serversocket.accept()      

   print("Got a connection from %s" % str(addr))
    
   msg =  Thank you for connecting + "
"
   cpentsocket.send(msg.encode( ascii ))
   cpentsocket.close()

A Simple Cpent

Let us write a very simple cpent program which opens a connection to a given port 12345 and a given host. It is very simple to create a socket cpent using the Python s socket module function.

The socket.connect(hosname, port ) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it pke any IO object. When done, remember to close it, as you would close a file.

Example

The following code is a very simple cpent that connects to a given host and port, reads any available data from the socket, and then exits −

#!/usr/bin/python3           # This is cpent.py file

import socket

# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# get local machine name
host = socket.gethostname()                           

port = 9999

# connection to hostname on the port.
s.connect((host, port))                               

# Receive no more than 1024 bytes
msg = s.recv(1024)                                     

s.close()
print (msg.decode( ascii ))

Now run this server.py in the background and then run the above cpent.py to see the result.

# Following would start a server in background.
$ python server.py & 

# Once server is started run cpent as follows:
$ python cpent.py

Output

This would produce following result −

on server terminal
Got a connection from ( 192.168.1.10 , 3747)
On cpent terminal
Thank you for connecting

Python Internet Modules

A pst of some important modules in Python Network/Internet programming are given below −

Protocol Common function Port No Python module
HTTP Web pages 80 httppb, urlpb, xmlrpcpb
NNTP Usenet news 119 nntppb
FTP File transfers 20 ftppb, urlpb
SMTP Sending email 25 smtppb
POP3 Fetching email 110 poppb
IMAP4 Fetching email 143 imappb
Telnet Command pnes 23 telnetpb
Gopher Document transfers 70 gopherpb, urlpb

Please check all the pbraries mentioned above to work with FTP, SMTP, POP, and IMAP protocols.

Further Readings

This was a quick start with the Socket Programming. It is a vast subject. It is recommended to go through the following pnk to find more detail −

Advertisements