Python's network programming

Source: Internet
Author: User

An operating system is a computer program that manages and controls the hardware and software resources of a computer. The essence of the Internet is a series of network protocols. The Internet protocol can be divided into seven layers according to function: should, table, meeting , transmission, net, number, object

Common physical devices per layer:

Transport Layer--"layer four switch, layer four router

Network layer-router, layer three switch

Data Link layer--"bridge, Ethernet switch, network card

Physical Layer--"repeater, hub, twisted pair

Physical Layer

Physical layer function: mainly based on electrical characteristics to send high and low voltage signals

Data Link Layer

The data link layer specifies how many bits of an electrical signal are set, meaning each group. (That is, define the way the electrical signals are grouped)

The Ethernet Protocol (Ethernet) provides:

。 A set of electrical signals forms a datagram, also called a "frame"

。 Each data frame is divided into two parts, header and data,

Header (head):

。 Source Address, 6 bytes

。 Destination Address, 6 bytes

。 Data type, 6 bytes

Data:

Shortest 46 bytes, up to 1500 bytes, head length +data length = Shortest 64 bytes, maximum 1518 bytes, Shard sent over maximum limit

MAC Address:

The source and destination addresses included in the head are: Ethernet specifies that devices that access the Internet must have a network card, and the address of the sending and receiving ends refers to the address of the network card, which is the MAC address

MAC Address: Each NIC is fired from the factory, the world's only MAC address, the length of 48-bit 2 binary, usually represented by 12-bit 16 binary number (the first six bits is the manufacturer number, the last six bits is the pipeline number)

Broadcasting:

With a MAC address, two hosts within the same network can communicate (one host obtains the MAC address of another host via the ARP protocol)

The ARP protocol is a broadcast way of sending packets that get the MAC address of the destination host.

The protocol works by knowing that each host's IP is known.

Example: Host 172.16.10.10/24 access 172.16.10.11/24

One: First differentiate your subnet by IP address and subnet mask

Scenario Packet Address

Target host Mac, target host IP, same subnet

Different subnet gateway Mac, destination host IP

Two: Analysis 172.16.10.10/24 and 172.16.10.11/24 are in the same network (if not the same network, then the target IP in the following table is 172.16.10.1, the Mac that gets the gateway via ARP)

SOURCE Mac destination Mac Source IP Destination IP data part

Send-side host Sender mac FF:FF:FF:FF:FF:FF 172.16.10.10/24 172.16.10.11/24 data

Three: This package will be broadcast in the sending side of the network in the transmission, all hosts received after unpacking, found that the target IP for their own, on the response, back to their Mac

Network layer

The world-wide internet is made up of isolated small local area networks, Ethernet can only be sent within the same LAN, a LAN is a broadcast domain, Ethernet broadcast packets can only be sent within a broadcast domain, cross-broadcast domain communication can only be forwarded through the route.

The problem is that you have to find a way to differentiate which broadcast domain the computer is in?

With routing (distributing packets to different broadcast domains/subnets), Macs are indistinguishable and are only vendor-related. Network layer function: Introduce a new set of addresses to distinguish different broadcast domains/subnets, which is the network address.

The IP address is divided into:

Network section: Identifying subnets

Host part: Identity host

The IP packet is divided into head and data, without having to define a separate field for the IP packet and put it directly into the data portion of the Ethernet packet. The head length is 20 to 60 bytes, the data length is 65515 bytes, and the Ethernet packet has a maximum of 1500 bytes, so if the IP packet is too long it will be divided into several packets to be sent separately.

Note: The simple IP address segment only identifies the type of IP address, from the network part or the host part can not identify the subnet in which an IP is located

Example: 172.16.10.1 and 172.16.10.2 are not sure that they are in the same subnet

Subnet Mask:

A subnet mask is a parameter that represents a subnet feature. It is formally equivalent to an IP address, is also a 32-bit binary number, its network portion is all 1, the host part is all 0. For example, IP address 172.16.10.1, if the network portion is known as the first 24 bits, the host part is the last 8 bits, then the subnet mask is 11111111.11111111.11111111.00000000, written in decimal is 255.255.255.0.

With the subnet mask, we can determine whether any two IP addresses are in the same subnet through the and method.

The purpose of IP protocol is to assign an IP address to each computer, and the other is to identify those addresses on the same subnet.

Transport Layer

The IP of the network layer is used for the area molecular Network, the Ethernet MAC is used to find the host, and an application on a machine is identified with a port, which is the number that the application associates with the network card.

Port range is 0-65535, 0-1023 is System-occupied port

TCP protocol is reliable transmission, TCP packet is no length limit, theoretically can be infinitely long, but for network efficiency, usually TCP packet length will not exceed the length of IP packet.

UDP protocol is unreliable transmission, the header only 8 bytes, the total length of not more than 65535 bytes, just put into the IP packet.

TCP protocol: Ethernet header IP Header TCP header data

UDP Protocol: Ethernet header IP header UDP header data

Application Layer

The role of the application layer is to specify the data format of the application.

Socket (socket)

The socket is an abstraction layer between the application layer and the transport layer, which abstracts the complex operations of the TCP/IP layer into a few simple interfaces to provide layer calls to enable the process to communicate in the network.

There are two types of sockets, which are file-based and network-based.

Server-side: First initializes the socket, then binds to the port (BIND), listens to the port (listen), calls accept blocking, waits for the client to connect. If the client initializes a socket and then connects to the server (connect), the connection between the client and the server is established if the connection is successful. The client sends the data, the server accepts and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction.

Service-Side socket functions

S.bind () binding (host, port number) to socket

S.listen () Start TCP listener

S.accept () passively accepts a TCP client connection, (blocking) waits for a connection to arrive

Client socket functions

S.connect () Active initialization of TCP server connections

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 () Receiving TCP data

S.send () sends TCP data (send data is lost when the amount of data to be sent is greater than the remaining space in the cache)

S.sendall () sends the full TCP data (essentially a cyclic call Send,sendall the data is not lost when the amount of data to be sent is greater than the remaining space in the buffer, and the call to send is sent until it is finished)

S.recvfrom () receiving UDP data

S.sendto () Send UDP data

S.getpeername () The address of the remote that is connected to the current socket

S.getsockname () address of the current socket

S.getsockopt () returns the parameters of the specified socket

S.setsockopt () Sets the parameters of the specified socket

S.close () Close socket

Lock-oriented socket method

S.setblocking () sets the blocking and non-blocking mode for sockets

S.settimeout () Sets the timeout period for blocking socket operations

S.gettimeout () Gets the timeout period for blocking socket operations

Functions for file-oriented sockets

S.fileno () The file descriptor of the socket

S.makefile () Create a file associated with the socket

TCP is connection-based, and you must start the server before you start the Client Connection server.

UDP is non-connected, no matter which end is first started.

Server

Import Socket
inp_port= (' 127.0.0.1 ', 8080)
bufsize=1024
Udp_server=socket.socket (Socket.af_inet,socket. SOCK_DGRAM)
Udp_server.bind (Inp_port)
While True:
Msg,addr=udp_server.recvfrom (BUFSIZE)
Print (MSG,ADDR)

Udp_server.sendto (Msg.upper (), addr)

Client

Socket
ip_port= (' 127.0.0.1 ', 8080)
bufsize=1024
Udp_client=socket.socket (Socket.af_inet,socket. SOCK_DGRAM)
While True:
Msg=input (' >> '). Strip ()
Msg
Continue
Udp_client.sendto (Msg.encode (' utf-8 '), Ip_port)
Msg,addr=udp_client.recvfrom (BUFSIZE)
Print (Msg.decode (' utf-8 '), addr)

Python's 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.