After reading this section, I suddenly got to know some incomprehension issues in the python network programming learning Notes (1). at least I understood what happened to socket. Here, we will not take notes on the origin of socket and directly go to the topic.
1. create a socket
To create a socket object, you must understand the communication type and protocol family. The communication type specifies the protocol used for data transmission. Protocols include IPv4, IPv6, IPX \ SPX, and AFP. For internet communication, the communication types are basically AF_INET (corresponding to IPv4 ). The protocol family generally indicates the SOCK_STREAM of TCP communication or the SOCK_DGRAM of UDP communication. Therefore, for TCP communication, the statement for establishing a socket connection is:
S = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
For UDP communication, the statement for establishing a socket connection is:
S = socket. socket (socket. AF_INET, SOCK_DGRAM)
2. connect to the socket
To connect to a socket, you must provide a tuple, including host (host name or IP address) and port (remote port). The code is as follows:
S. connect ("www.baidu.com", 80)
3. search for the port number
The getservbyname () function can be used in the socket library to query the port number. Generally, two parameters are required: one is the protocol name, such as http, smtp, pop3, and the other is the port name, such as tcp and udp.
For example:
Import socket
S = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
Port = socket. getservbyname ('http', 'tcp ')
The return value of port is 80. If Changed:
Port = socket. getservbyname ('smtp ', 'tcp ')
The return value of port is 25.
4. obtain information from socket
After a socket connection is established, you can use getsockname () to obtain its own IP address and port number, or use getpeername () to display the IP address and port number of the remote machine.
For example, in python shell
>>> Import socket
>>> S = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
>>> Port = socket. getservbyname ('http ', 'tcp ')
>>> S. connect ('www .baidu.com ', port ))
>>> Print s. getsockname ()
('192. 168.87.138 ', 192)
>>> Print s. getpeername ()
('1970. 181.111.147 ', 80)
Socket module class method
Class method description
Socket low-layer network interface (each bsd api)
Socket. socket (family, type) is created and a new socket object is returned.
Socket. getfqdn (name) converts an IP address string separated by dots into a complete domain name
Socket. gethostbyname (hostname) resolves the host name into an IP address string separated by dots
Socket. fromfd (fd, family, type) creates a socket object from the existing file descriptor
Socket module instance method
Instance method description
Sock. bind (adrs, port) binds the socket to an address and port
Sock. accept () returns a client socket (with the client address information)
Sock. listen (backlog) sets the socket to the listening mode to listen to external connection requests of the backlog
Sock. connect (adrs, port) connects the socket to the defined host and port
Sock. recv (buflen [, flags]) receives data from the socket, with a maximum of buflen characters
Sock. recvfrom (buflen [, flags]) receives data from the socket. it contains a maximum of buflen characters and returns the remote host and port number of the data source.
Sock. send (data [, flags]) send data through socket
Sock. sendto (data [, flags], addr) sends data through socket
Sock. close () close socket
Sock. getsockopt (lvl, optname) to obtain the value of the specified socket option
Sock. setsockopt (lvl, optname, val) sets the value of the specified socket option
Example:
>>> Import socket
>>> Socket. gethostbyname ('www .baidu.com ')
'1970. 181.111.147'
>>> Socket. gethostbyname ('www .126.com ')
'1970. 125.50.22'
>>> Socket. getfqdn ('2017. 125.50.22 ')
'1970. 125.50.22'
Here, getfqdn cannot return the domain name?
5. handle errors
For error exception handling, try and retry T statements are mainly used. For example, modify gopherclient. py in python network programming learning Note (1:
The code is as follows:
#-*-Coding: cp936 -*-
# Modify by xiaowuyi
Import socket, sys
Port = 70
Host = sys. argv [1]
Filename = sys. argv [2]
Try:
S = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
Failed T Socket. error, e:
Print "socket creation error: % s" % e
Try:
S. connect (host, port ))
Handle T socket. gaierror, e:
Print "host or port error: % s" % e
Failed T socket. error, e:
Print "connection error: % s" % e
Try:
S. sendall (filename + "\ r \ n ")
Failed T socket. error, e:
Print "data sending error: % s" % e
Sys. exit (1)
While 1:
Try:
Buf = s. recv (2048)
Failed T socket. error, e:
Print "receiving error: % s" % e
Sys. exit (1)
If 'does not exist' in buf:
Print "% s file does not exist" % filename
Else:
If not len (buf ):
Break
Sys. stdout. write (buf)
The running result is:
C: \> python gopherclient. py quux.org/wh.txt
Connection error: [Errno 10060]
Data sending error: [Errno 10057] because the socket is not connected and
Socket reporting)
C: \> python gopherclient. py quux.org wh.txt
Wh.txt file does not exist
========================================================== ========================================================== ========================================================
Add python network programming learning Notes (1)
In note 1, the system prompts an error when running python gopherclient. py quux.org under dos, and finally understands. The error is because the file name is missing. For example, if you have whatsnew.txtin quux.org/, you can run Python gopherclient. py quux.org whatsnew.txt in dos. In this case, all contents of whatsnew.txt will be listed.