Python network programming (OSI model, network protocol, TCP)

Source: Internet
Author: User
Tags get ip

Objective:

What is a network?

The network is composed of nodes and lines, which represent many objects and their interconnections.

In mathematics, the network is a kind of diagram, which is generally regarded as referring to weighted graphs.

In addition to the mathematical definition of the network, there are specific physical meanings, that is, the network is from some of the same type of practical problems abstracted from the model

In the field of computer, the network is the virtual platform of information transmission, receiving and sharing, through which the information of each point, polygon and body is connected together, so as to realize the sharing of these resources .

The internet is the most important invention in the history of mankind, which improves the development of science and technology and human society.

Before the 1999, it was generally assumed that the structure of the network was random. But as Barabasi and Watts discovered the scale and small world characteristics of the network in 1999 and published their findings in the world-famous science and nature, they realized the complexity of the network.

Through the use of text reading, image viewing, video playback, download transmission, games, chat and other software tools from text, pictures, sound, video and other aspects to bring people a very rich life and good enjoyment.

Network Purpose:What is the purpose of network transmission?
    • That's right: data transfer
because of the complexity of the network and a variety of application hardware and so on mismatch reason and coding is a reason you have I have my will lead to conflicts and other issues so appeared: ISO (International Organization for Standardization) ISO is why?
  • He's a non-profit international organization. The organization developed an Internet standard system for computers or communication systems
  • Called the OSI model includes not only a series of abstract terms or concepts, but also specific protocols
  • OSI Public layer Seven:
    1. Application Layer : provision of user services , specific content specified by the program
    2. presentation Layer : provides encryption and compression optimizations for data
    3. Session Layer : Make sure to set up the application link and select the transport service
    4. Transport Layer : provides data transfer services for flow control
    5. Network layer : route selection , network interconnection
    6. Link Layer : provides link switching , sending of specific messages
    7. Physical layer : physical hardware, interfaces, network card provisions
or four-layer model:
    1. Application Layer: Application Layer presentation layer Session layer
    2. Transport Layer: Transport Layer
    3. Network layer: Network layer
    4. Physical link layer: Link Layer and physical layer
or five-tier model (TCP/IP model):
    1. Application Layer: Application Layer presentation layer Session layer
    2. Transport Layer: Transport Layer
    3. Network layer: Network layer
    4. Link Layer: Link layer
    5. Physical Layer: Physical layer
  OSI Model Benefits
    • Separate functions to reduce coupling in the network,
    • Use the development process more clearly and each part
Cohesion Poly-low coupling:
    1. High cohesion: Each module functions as single as possible, does not have multiple function doping
    2. Low coupling: Minimizing the correlation between each module
Network protocol:
    • The rules that must be complied with in the network communication,
    • such as what connection is established, how message structure is parsed, etc.
    • Application layer: TFTP (file transfer), HTTP (Hypertext Transfer Protocol), DNS (domain name resolution), SMTP (mail transport)
    • Transport layer: TCP, UDP
    • Network layer: IP
    • Physical Layer: IEEE
Ipython3:socket Module Network-related concepts:Network host: Determine a host on the network
    1. Local use: 127.0.0.1 or "localhost"
    2. Network address: "0.0.0.0" or "172.168.40.53"
    • Ifconfig: View Native IP (ens33: Local IP lo: local pensive)
    • In Ipconfig:windoes
    • Socket.gethostname (): Gets the native host name
    • Socket.gethostbyname (' tedu '): Get IP with hostname
    • Socket.gethostbyname (' localhost '): Get local IP
Common IP Address:
    1. IPV4: Dotted Decimal Example: 192.168.1.3 value 0~255 (32 bit)
    2. ipv6:128 bit
Network Connectivity Test Ping172.18.32.47 Special IP
    1. 127.0.0.1 Local IP Test
    2. 0.0.0.0 automatic use of locally available NIC IP
    3. 192.168.1.0 Representative Network Segment
    4. 192.168.1.1 is usually the gateway address
    5. 192.168.1.255 Broadcast Address
Access host IP address:socket.gethostbyaddr (' 127.0.0.1 ')(‘ localhost‘, [], [‘ 127.0.0.1‘]) Host aliases IP Address   IP 16 binary conversion:
    • Socket.inet_aton (' 192.168.1.2 ')
    • B ' \xc0\xa8\x01\x02 '
    • Socket.inet_ntoa (b ' \xc0\xa8\x01\02 ')
    • ' 192.168.1.2 '
Domain Name:
    • Refers to the name of the network server address on the network
Port number:
    • The port number is part of the address, in one system per network ( differentiated application IP)
    • Application listens on different ports to get the corresponding port pass information
    • Value range: 1---------65535
    • 1---------2,551 Common ports (well-known program occupancy)
    • ------1023 System Port
    • 1024x768-----65535 own port
get the port of the application:
    1. Socket.getservbyname (' ssh ')
    2. 22
    1. Socket.getservbyname (' MySQL ')
    2. 320W
Transport Layer Services:   Connection-oriented transport service (TCP protocol):
    • Transmission characteristics:
    • Reliable data transfer:
    • reliability: No disorder, no error, no duplication, no loss
    • Connection and disconnection required before and after data transfer
    • The process of establishing a connection for the transport service: ' three handshake '
  1. The client sends a link request to the server
  2. The server accepts a request for confirmation and returns a confirmation message.
  3. Client receives server reply final confirmation link
    • The process of disconnecting a link for a transport service: ' four Waves '
    1. The active party sends a message informing the passive party to break the link
    2. The passive party responds to the message, indicating that it has received the request and is ready to disconnect
    3. The passive party sends the message again, indicating that it is ready for processing and can disconnect
    4. The active party sends the confirmation message, disconnects the link
  • Application situation:
  • Suitable for transferring large content or files, network is good,
  • Situations where transmission reliability needs to be ensured
  • e.g. Information chat, file upload download, mail, Web Access
for a non-connected transport service (UDP protocol):
    1. No guarantee of transmission reliability
    2. No process to establish connection and disconnection
    3. More freedom to send and receive data
    • Applicable situation:
    • Network situation is poor, the reliability requirements are not high, send and receive messages on both ends
    • e.g.: Network video, group chat, broadcast, etc.
Socket Socket Programming: Objective:
    • Socket programming interface provided by programming language
    • TCP/UDP-based programming can be done more easily
Socket:
    • is a programming tool to accomplish these goals
Socket Category:1. Streaming Sockets ( Sock_stream):
    • Transport Layer socket-based protocol communication
    • Transport-Flow sockets for connection-reliable transport of TCP
2. Datagram Sockets ( Sock_dgram):
    • Transmit datagram sockets for non-connected unreliable transport UDP
3. Low-level sockets (Sock_ram):
    • Accessing the underlying protocol sockets
TCP service side: Import Socket 1. Create Sockets (Functions): Socket.socket(sock_family = af_inet, Sock_type = sock_stream, proto = 0) Features:
    • Creating sockets
Parameters:
    • sock_family address Family type Af_inet:ipv4 network communication
    • Sock_tpye: Socket type Sick_stream: Streaming sock_dgram: Datagram
    • Proto: typically 0 selected sub-protocol type
    • Return value: Returns a Socket object
2. Bind address (function): sockfd.bind (addr) Features:
    • Binding address
Parameters:
    • Addr---> Tuples (IP, Port) ("0.0.0.0", 8888)
3. Set the listener socket: Sockfd.listen (n) Features:
    • To set a socket as a listening socket, create a listening queue
Parameters:
    • Listening Queue Size
    • One listener socket can connect multiple clients
4. Wait for the client link to be accepted: connfd,addr = sockfd.accept () blocking State Features:
    • Blocking wait and processing client links
return Value:
    1. CONNFD: New socket for communicating with clients
    2. addr: The address of the linked client (IP, port)
Blocking Functions
    • When the program runs to the blocking function location, if a condition
    • Suspend the program until the condition is reached and the end is blocked
- 5. Sending and receiving messages:data = Connfd.recvbuffersizeFeatures:
    • Accept Message
Parameters:
    • Size bytes to accept messages at one time
    • Return value: Returns the accepted content
n = connfd.send (data) Features:
    • Send Message
Parameters:
    • What to send (bytes format)
    • Return value: Returns the number of bytes actually sent
6. Close the socket SOCKFD. close() Client: 1. Creating Sockets(same as Service end socket type) 2. Initiating a link Connect (addr) Features:
    • Initiating a link to the server
Parameters:
    • Server address ( tuple )
3. Messaging 4. Closing sockets ExampleService side:
from socket import *# 创建套接字对象sockd = socket()# 绑定IP地址sockd.bind(("127.0.0.1", 6666))# 设置监听套接字sockd.listen(5)# 等待客户端链接cond, addr = sockd.accept()# 接受客户端消息(单次1024字节)data = cond.recv(1024)print(data.decode())# 发送消息cond.send(b"Hello, I‘m the server")# 关闭套接字cond.close()sockd.close()
Here the native test can use two Telnet commands to link the server side test

Server:
from socket import *# 创建套接字sockfd = socket(AF_INET, SOCK_STREAM)# 绑定地址sockfd.bind(("0.0.0.0", 8888))# 设置监听sockfd.listen(5)# 等待客户端链接print("waiting for connect....")conn, addr = sockfd.accept()print("Connect from", addr)print("Connect from", conn)# 消息收发while True:    data = conn.recv(1024)    if data.decode() == "":        n = conn.send(b"Bey")        break    print("Receive", data.decode())    n = conn.send(b"Receive your message")    print("send %d" % n)# 关闭套接字conn.close()sockfd.close()

Client:
# tcp_client.pyfrom socket import *sockfd = socket()sockfd.connect(("172.18.32.31", 8888))while True:    msg = input("Msg>>")    if msg == "":        break    sockfd.send(msg.encode())    data = sockfd.recv(1024)    # if msg == "Bye":    #     break    print(data.decode())sockfd.close()


Simple Message transfer:

Python network programming (OSI model, network protocol, TCP)

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.