Socket to create a network client

  • 2020-04-02 13:44:00
  • OfStack

1. Establish socket

Establishing a socket object requires understanding the type of communication and the protocol family. The communication type specifies what protocol is used to transmit the data. Examples of protocols include IPv4, IPv6, IPX\SPX, and AFP. For Internet communication, the communication type is basically AF_INET (corresponding to IPv4). The protocol family generally represents the SOCK_STREAM of TCP communication or the SOCK_DGRAM of UDP communication. Therefore, for TCP communication, the statement to establish a socket connection is:
S = socket. The socket (socket. AF_INET, socket. SOCK_STREAM)
For UDP communication, the statement to establish a socket connection is:
S = socket. The socket (socket. AF_INET SOCK_DGRAM)

2. Connect to socket

To connect to the socket, you need to provide a tuple, including host (hostname or IP) and port (remote port), similar to the code:
S.c onnect ((" www.baidu.com ", 80)

3. Look for a port number

Getservbyname () function in the socket library can query the port number, generally requires two parameters: one is the protocol name, such as HTTP, SMTP, pop3, etc., one is the port name, such as TCP, udp

Such as:

Import the socket
S = socket. The socket (socket. AF_INET, socket. SOCK_STREAM)
Port = socket. Getservbyname (' HTTP ', 'TCP)
The return value of port is 80. If changed to:
Port = socket. Getservbyname (' SMTP ', 'TCP)
The return value of port is 25.

4. Get information from socket

Once a socket connection is established, you can either get your own IP address and port number through getsockname() or display the IP address and port number of the remote machine through getpeername().
In the python shell

> > > Import the socket
> > > S = socket. The socket (socket. AF_INET, socket. SOCK_STREAM)
> > > Port = socket. Getservbyname (' HTTP ', 'TCP)
> > > S.c onnect ((' www.baidu.com ', the port)
> > > Print s.g etsockname ()
(' 192.168.87.138, 3213)
> > > Print s.g etpeername ()
(' 220.181.111.147, 80)

Socket module class method
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 the dot-delimited IP address string into a full domain name
Socket.gethostbyname (hostname) resolves the hostname into a dotted number delimited IP address string
Socket.fromfd (fd, family, type) creates a socket object from an existing file descriptor

Socket module instance method

Example method description
Sock.bind ((adrs, port)) binds the socket to an address and port
Sock. Accept () returns a client socket (with address information on the client side)
Sock. Listen (backlog) sets the socket to listen for incoming connection requests from the backlog
Sock. Connect ((adrs, port)) connects the socket to the defined host and port
Sock. Recv (buflen[, flags]) receives data from a socket with a maximum of buflen characters
Sock.recvfrom (buflen[, flags]) receives data from a socket of up to buflen characters and returns the remote host and port number of the data source
Sock. Send (data[, flags]) sends data over a socket
Sock. Sendto (data[, flags], addr) sends data over a socket
The sock. The close () close the socket
Sock.getsockopt (LVL, optname) gets the value of the specified socket option
Sock.setsockopt (LVL, optname, val) sets the value of the specified socket option

For example:
> > > Import the 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'
So getfqdn can't return the domain name, right?

5. Handle errors
The handling of error exceptions is mainly done with try and except statements. For example, the gopherclient.py in python network programming notes (1) is modified as follows:


# -*- coding: cp936 -*-
##modify by  Small WuYi 
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 " To establish 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+"rn")
except socket.error,e:
    print " Data sending error: %s" %e
    sys.exit(1)

while 1:
    try:
        buf=s.recv(2048)
    except 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] due to socket not connected and (when
When socket is reported)

C: \ > Python gopherclient. Py quux.org wh. TXT
The wh.txt file does not exist

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Add to python network programming study note (1)
In note 1, running python gopherclient.py quux.org under DOS prompted an error. The error was due to the missing file name. If you have whatsnew.txt at quux.org/, then run python gopherclient.py quux.org whatsnew.txt under DOS. The contents of whatsnew.txt are all listed.


Related articles: