Python Network Programming Learning Notes (II): Socket set up network client _python

Source: Internet
Author: User
Tags connect socket instance method socket error

1. Establish socket

Creating a socket object requires clarifying the type of communication and the Protocol family. The type of communication indicates what protocol is used to transmit data. Examples of agreements include IPv4, IPV6, ipx\spx, AFP. For Internet traffic, the type of communication is basically af_inet (and IPv4). The protocol family generally represents the sock_stream of TCP traffic or the sock_dgram of UDP traffic. So for TCP communication, the statement to establish a socket connection is:
S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
For UDP traffic, the statement that establishes a socket connection is:
S=socket.socket (Socket.af_inet,sock_dgram)

2. Connect socket

The connection socket needs to provide a tuple, including host name or IP, and port (remote port), similar to the following code:
S.connect ("www.baidu.com", 80)

3, find the port number

The socket library using the Getservbyname () function can query the port number, generally requires two parameters: first, the protocol name, such as HTTP, SMTP, POP3, and so on, one is the port name, such as TCP, UDP

For example:

Import socket
S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Port=socket.getservbyname (' http ', ' TCP ')
Port has a return value of 80. If read:
Port=socket.getservbyname (' SMTP ', ' TCP ')
Port has a return value of 25.

4, from the socket to obtain information

After you establish a socket connection, you can obtain its own IP address and port number by getsockname (), or you can display the IP address and port number of the remote machine by Getpeername ().
For example: in the 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 ', 3213)
>>> Print S.getpeername ()
(' 220.181.111.147 ', 80)

class method of Socket module
Class method Description
Socket Low-level network interface (per BSD API)
Socket.socket (family, type) creates and returns a new socket object
SOCKET.GETFQDN (name) converts an IP address string separated by a dot number into a full domain name
Socket.gethostbyname (hostname) resolves the host name to a string of IP addresses separated by a dot number
SOCKET.FROMFD (FD, family, type) creates a socket object from an existing file descriptor

instance method of Socket module

Instance method description
Sock.bind ((ADRs, port) binds the socket to an address and port
Sock.accept () Returns a client socket (with the client-side address information)
Sock.listen (backlog) sets the socket into a listening mode, capable of listening for backlog incoming connection requests
Sock.connect ((ADRs, port) connects the socket to the defined host and port
SOCK.RECV (buflen[, flags) receives data from the socket, up to Buflen characters
Sock.recvfrom (buflen[, flags) receives data from the socket, up to Buflen characters, and returns the remote host and port number of the data source
Sock.send (data[, flags) sends data via socket
Sock.sendto (data[, flags], addr) Send data via socket
Sock.close () Close socket
Sock.getsockopt (LVL, optname) Gets the value of the specified socket option
Sock.setsockopt (LVL, optname, Val) Set the value of the specified socket option

Example:
>>> Import Socket
>>> socket.gethostbyname (' www.baidu.com ')
' 220.181.111.147 '
>>> socket.gethostbyname (' www.126.com ')
' 123.125.50.22 '
>>> socket.getfqdn (' 123.125.50.22 ')
' 123.125.50.22 '
Here Getfqdn but can't return domain name?

5, processing errors
The main thing about handling error exceptions is to use try, except statements. For example, modify the gopherclient.py in the Python Network Programming Learning Notes (1):

Copy Code code as follows:

#-*-coding:cp936-*-
# #modify by the small five righteousness
Import Socket,sys
Port =70
HOST=SYS.ARGV[1]

FILENAME=SYS.ARGV[2]

Try
S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Except Socket.error,e:
Print "Create socket Error:%s"%e

Try
S.connect ((Host,port))
Except Socket.gaierror,e:
Print "Host or port error:%s"%e
Except Socket.error,e:
Print "Connection error:%s"%e

Try
S.sendall (filename+ "\ r \ n")
Except Socket.error,e:
Print "Data send error:%s"%e
Sys.exit (1)


While 1:
Try
BUF=S.RECV (2048)
Except Socket.error,e:
Print "Receive 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 results of the operation are:

C:\>python gopherclient.py Quux.org/wh.txt
Connection error: [Errno 10060]
Data send error: [Errno 10057] because the socket is not connected and (when
When the socket was reported)

C:\>python gopherclient.py quux.org Wh.txt
Wh.txt file does not exist

=============================================================================================================== ========
Add to the Python Network Programming Learning notes (1)
Note 1 in the DOS run Python gopherclient.py quux.org system prompts the problem of error, finally understood. The reason for the error is the missing filename. If there is whatsnew.txt in quux.org/, then run Python gopherclient.py quux.org whatsnew.txt in DOS. This will list the contents of the Whatsnew.txt.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.