Python basic article "14th": Network programming

Source: Internet
Author: User

1. Sockets
A socket is a combination of a source IP address and a destination IP address and a source port number and destination port number. A networked application must create a socket before any communication can begin. Just like the phone jack, there is no way to communicate without it.
It is an abstract representation of the endpoint in the network communication process and contains five kinds of information that must be used for network communication: the protocol that the connection uses, the IP address of the local host, the protocol port of the local process, the IP address of the remote host, and the protocol port of the remote process.
The English name of the socket is the socket

Socket, which is the basic operation unit of TCP/IP-supported network communication, can be regarded as the endpoint of two-way communication between different hosts, which is simply a kind of convention of communication, and the correlation function in socket is used to complete the communication process.
The very very simple example below: Socket=ip address+ tcp/udp + port.

The 3 types of sockets for commonly used TCP/IP protocols are shown below.

Stream Sockets (SOCK_STREAM):
Stream sockets are used to provide connection-oriented, reliable data transfer services. The service will ensure that the data can be error-free, non-repeatable, and sequentially received. The reason that a streaming socket can achieve reliable data services is because it uses the Transmission Control Protocol,
That is, the TCP (the transmission Control Protocol) protocol.

Packet sockets (SOCK_DGRAM):
A packet socket provides a non-connected service. The service does not guarantee the reliability of data transmission, it is possible to lose or duplicate data during transmission, and can not guarantee the sequential receipt of data. Packet sockets using UDP (User Datagram Protocol)
protocol for the transmission of data. Because the data packet socket cannot guarantee the reliability of the data transmission, it is necessary to do the corresponding processing in the program for the possibility of the loss.

Original socket (SOCK_RAW):
Raw Sockets (Socket_raw) allow direct access to lower-level protocols, such as IP, ICMP protocol, which is often used to verify new protocol implementations, or to access new devices configured in existing services, because RAW sockets have the freedom to control multiple protocols under Windows.
can control the transmission mechanism of the network bottom, so the original socket could be applied to manipulate the network layer and the Transport layer application. For example, we can use raw sockets to receive ICMP, IGMP protocol packets that are sent to the native, or to receive IP packets that the TCP/IP stack cannot handle.
can also be used to send some custom header or custom protocol IP packets. Network monitoring technology relies heavily on Socket_raw

The difference between the original socket and the standard socket (the standard socket refers to the flow socket and the packet socket described earlier) is that the original socket can read and write IP packets that are not processed by the kernel, and the stream sockets can read only the data of the TCP protocol, and the packet sockets can read only the UDP coprocessor
The data of the discussion. Therefore, if you want to access other protocols to send data, you must use the original socket.

2. Socket address: Host and port
If the socket is compared to the telephone socket-the most basic structure of communication, the host and port like the area code and phone number of a pair of combinations, with the ability to call the hardware is not enough, you need to know who to call, where to fight. Network communication The most recent composition is the host and port.
The network legal port range is between 0~65535, and the system retains the port below 1024.

3. Connection-oriented to no connection
Connection-oriented and non-connection protocol processing methods, connection-oriented and non-connection protocol connection-oriented and connectionless protocols communication protocol is either connection-oriented or non-connected. This depends on whether the sender of the message needs to be associated with the receiving party
Contact to maintain a conversation (connection-oriented), or to send a message without any prior contact (no connection) and want the recipient to be able to receive all the content sequentially. These methods reveal two ways to realize communication on the network.

Connection oriented
Connection-oriented sockets, that is, make sure to make a connection before communicating, like calling a friend. This is also referred to as a ' virtual circuit ' or ' flow socket '. The connection-oriented communication approach provides a reliable, repeatable data transfer with no data boundaries
This means that each message to be sent may be split into multiple copies, each of which will arrive at the destination correctly, and be re-assembled in order to pass to the waiting application.
The primary protocol for implementing this connection is the Transmission Control Protocol (TCP). To create a TCP socket, you have to specify the socket type Sock_stream at creation time (stream sockets are connection-oriented). The TCP socket uses the name Sock_stream, which expresses its feature as a stream socket.
Because these sockets use Internet Protocol (IP) to find hosts in the network, the entire system that is formed is typically described by a combination of two protocol (TCP and IP) names, which is TCP/IP.
Cons: There is a need to provide some assurance, and to maintain the virtual circuit connection, which is an additional burden.

No connection
No connection is the opposite of connection-oriented, which means that communication can be done without establishing a connection, but the order in which the data arrives is not guaranteed. The datagram preserves the data boundaries, which means that the data is sent throughout.
Using datagrams to transfer data is just like a postal service. Messages do not necessarily arrive in the order they were sent, and in fact the messages may be lost. And even sending messages over the network is repeated, which adds to the complexity.
The primary protocol for implementing this connection is the User Datagram Protocol (UDP). To create a UDP socket, you specify that the socket type is SOCK_DGRAM when you create it. Because these sockets use an Internet protocol to find hosts in a network, the entire system is typically made up of these two
Protocol (UDP and IP) names are described together, i.e. UDP/IP

4. Network programming
With the above content, the socket module is used. The socket () function in the module is used to create the socket. Sockets also have their own set of functions to provide socket-based network traffic.
Import socket

# Create sockets using the Socke.socke () function
# Sockets (Self, family, type, proto, Fileno)
# Self: socket
# family: type of socket
# type: # Types of connections (connection-oriented or no-connection)
# Proto: Prototype I don ' t know
# fileno:i don ' t know

Tcpsock = Socket.socket (socket.af_inet,socket. SOCK_STREAM) #tcp/IP Sockets
Print (Tcpsock,type (tcpsock))

Udpsock = Socket.socket (socket.af_inet,socket. SOCK_DGRAM) #udp/IP Sockets
Print (Udpsock,type (udpsock))

5. Socket object (built-in) method
Function description

Server-side sockets

S.bind () binds the address (host,port) to the socket and, under Af_inet, represents the address in the form of a tuple (host,port).
S.listen () starts TCP snooping. The backlog specifies the maximum number of connections that the operating system can suspend before rejecting the connection. This value is at least 1, and most applications are set to 5.
S.accept () passively accepts TCP client connections, (blocking) waits for a connection to arrive

Client sockets

S.connect () actively initializes the TCP server connection. The format of the general address is a tuple (hostname,port) and returns a socket.error error if there is an error in the connection.
Extended version of the S.CONNECT_EX () connect () function, which returns an error code instead of throwing an exception when an error occurs

Socket functions for public use

S.RECV () Receives TCP data, the data is returned as a string, and bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.
S.send () Sends the TCP data, sending the data in the string to the connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string.
S.sendall () sends TCP data in full and sends TCP data in full. Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.
S.recvform () receives UDP data, similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data.
S.sendto () sends UDP data, sends the data to the socket, address is a tuple in the form of (Ipaddr,port), and specifies the remote address. The return value is the number of bytes sent.
S.close () Close socket

Module-oriented Socket description

S.getpeername () Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).
S.getsockname () returns the socket's own address. Typically a tuple (ipaddr,port)
S.setsockopt (Level,optname,value) Sets the value of the given socket option.
S.getsockopt (Level,optname[.buflen]) returns the value of the socket option.
S.settimeout (timeout) sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as Connect ())
S.gettimeout () Returns the value of the current timeout, in seconds, or none if the timeout period is not set.

File-oriented socket description

S.fileno () returns the file descriptor of the socket.
S.setblocking (flag) If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to block mode (the default). In nonblocking mode, if the call recv () does not find any data, or the Send () call cannot send the data immediately, the Socket.error exception is raised.
S.makefile () Create a file associated with the socket

6. Create a TCP server
SS = socket () #创建服务器套接字
Ss.bind () #把地址绑定到套接字上
Ss.listen () #监听连接
Inf_loop: #服务器无线循环
cs = ss.accept () #接收客户端连接
Comm_loop:
CS.RECV (1024x768)/cs.send () #对话 (Receive and send)
Cs.colse () #关闭客户端套接字
Ss.close () #关闭服务器套接字

#!/usr/bin/env python3#-*-coding:utf-8-*-#serverimport socket# using the Socke.socke () function to create a socket # socket (self, family, type, pro  To, Fileno) # Self: socket# family: Type of Socket # type: # connection type (connection-oriented or no-connection) # Proto: Prototype I don ' t know# fileno:i don ' t know# tcpsock = Socket.socket (Socket.af_inet,socket. SOCK_STREAM)      #tcp/IP Socket # print (Tcpsock,type (Tcpsock)) # # Udpsock = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)       #udp/IP Socket # print (Udpsock,type (udpsock)) SK = Socket.socket ()                #创建TCP/IP socket sk.bind (' 127.0.0.1 ' , 9999,))        #绑定服务端的IP和端口sk. Listen (5)                        #开始监听 "5" Maximum of 5 clients waiting while True:                         #服务端永远等待客户端连接    conn, address = Sk.accept ()         #接收客户端的请求 (blocking, waiting), passing the connection and address information received to the client to the variable    print (address, conn)

Import socketobj = Socket.socket ()                   #创建TCP/IP Socket Obj.connect ((' 127.0.0.1 ', 9999))        #客户端指定连接的服务器地址obj. Close ()                             #关闭客户端连接

This is simply the establishment of a connection

Python basic article "14th": Network programming

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.