SoFunction
Updated on 2024-11-15

python network programming study notes (2): socket to establish a network client

1、Establish socket

Creating a socket object requires figuring out the communication type and protocol family. The communication type specifies what protocol is used to transfer data. Examples of protocols include IPv4, IPv6, IPX/SPX, AFP, etc. For Internet communication, the communication type is basically AF_INET (corresponding to IPv4). The protocol family generally indicates SOCK_STREAM for TCP communication or SOCK_DGRAM for UDP communication. so for TCP communication, the statement to establish a socket connection is:
s=(socket.AF_INET,socket.SOCK_STREAM)
For UDP communication, the statement to establish a socket connection is:
s=(socket.AF_INET,SOCK_DGRAM)

2、Connect socket

To connect to a socket you need to provide a tuple, including host (hostname or IP) and port (remote port), similar to the code for:
(("",80)

3. Finding the port number

socket library using getservbyname() function can query the port number, generally need two parameters: one is the protocol name, such as http, smtp, pop3, etc., one is the port name, such as tcp, udp

Example:

import socket
s=(socket.AF_INET,socket.SOCK_STREAM)
port=('http','tcp')
The return value of port is 80. if changed to:
port=('smtp','tcp')
The return value of port is 25.

4. Getting information from socket

After establishing a socket connection, you can get its own ip address and port number via getsockname(), or you can display the ip address and port number of the remote machine via getpeername().
E.g. in the python shell

>>> import socket
>>> s=(socket.AF_INET,socket.SOCK_STREAM)
>>> port=('http','tcp')
>>> (('',port))
>>> print ()
('192.168.87.138', 3213)
>>> print ()
('220.181.111.147', 80)

Socket Module Class Methods
Class Method Description
Socket Low-level network interface (per BSD API)
(family, type) Creates and returns a new socket object.
(name) Converts a dot-separated IP address string into a full domain name
(hostname) Parses the hostname into a dot-separated IP address string.
(fd, family, type) creates a socket object from an existing file descriptor

Example Methods for the Socket Module

Example Method Description
( (adrs, port) ) binds the socket to an address and port
() returns a client socket (with address information for the client side)
(backlog) Sets the socket to listen mode, so that it can listen for connection requests from the backlog.
( (adrs, port) ) connects the socket to the defined host and port
( buflen[, flags] ) Receive data from socket, up to buflen characters
( buflen[, flags] ) Receives data from the socket, up to buflen characters, and returns the remote host and port number from which the data originated
( data[, flags] ) send data over socket
( data[, flags], addr ) send data over socket
() closes the socket
( lvl, optname ) gets the value of the specified socket option
( lvl, optname, val ) sets the value of the specified socket option

Examples:
>>> import socket
>>> ('')
'220.181.111.147'
>>> ('')
'123.125.50.22'
>>> ('123.125.50.22')
'123.125.50.22'
Here getfqdn but can't return the domain name?

5. Handling errors
Regarding the handling of error exceptions, the main thing is to use try, except statements. If you make a little modification in python network programming study notes (1):

Copy Code The code is as follows.

# -*- coding: cp936 -*-
##modify by Xiao * or Little Five Righteousnesses (c. fifth century AD), Chinese revolutionary leader of the Boxer rebellion
import socket,sys
port =70
host=[1]

filename=[2]

try:
    s=(socket.AF_INET,socket.SOCK_STREAM)
except ,e:
print "Error establishing socket: %s"%e

try:
    ((host,port))
except ,e:
print "host or port error: %s" %e
except ,e:
print "Connection error: %s" %e

try:
    (filename+"\r\n")
except ,e:
print "Error sending data: %s" %e
    (1)


while 1:
    try:
        buf=(2048)
    except ,e:
print "Receiving error: %s"%e
        (1)
    if 'does not exist' in buf:
print "%s file does not exist" %filename
    else:
        if not len(buf):
            break
        (buf)

The result of the run is:

C:\>python /
Connection error: [Errno 10060]
Data transmission error: [Errno 10057] The data transmission error occurred because the socket was not connected and (when the
when reporting sockets)

C:\>python
File does not exist

=======================================================================================================================
Additions to python network programming study notes (1)
The problem with running python under dos in note 1 where the system prompted an error was finally understood. The reason for the error was that the filename was missing. As in / there, so run python under dos . This will list all the contents of the