Analysis of TCP/IP protocol families in iOS & amp; Socket, iostcp

Source: Internet
Author: User

Analysis of TCP/IP protocol families in iOS & Socket, iostcp
Introduction

This article mainly reviews TCP/UDP, HTTP, and Socket in the TCP/IP protocol family.(-- This article is very dry and has been brewing for a long time! Can you watch it patiently? O_o)

In this article, I listed common protocols in the TCP/IP family. Today, the main character is the transport layer protocol.

The Transport Layer is the most important and critical Layer in the OSI (Layer-7 model). It is responsible for the overall data transmission and data control Layer, the transport layer provides an end-to-end data exchange mechanism (the application registers a port number on the NIC) to check the group number and order. The transport layer provides reliable transmission services for the upper layer, such as the session layer, and provides reliable destination site information for the network layer.

Protocols in the transport layer
  • Transport Layer provides session and datagram communication services for the application layer.
  • The transport layer is responsible for the OSI transport layer.
  • The Core protocols of the transport layer are TCP and UDP.

    TCP provides one-to-one and connection-oriented reliable communication services. TCP establishes a connection, sorts and confirms sent packets, and restores lost packets during transmission. Unlike TCP, UDP provides one-to-one or one-to-many non-connection unreliable communication services.
    In either TCP/IP or OSI reference model, any lower layer of the adjacent two layers serves as the service provider and the upper layer serves as the service caller. The services provided by the lower layer for the upper layer can be divided into two types: connection-oriented and connectionless services.

  • Connection-oriented network services

    A connection-oriented network service, also known as a Virtual Circuit service, has three stages: network connection establishment, data transmission, and network connection release. It is a reliable packet grouping method for ordered transmission and is suitable for transmission of specified objects, long packets, and sessions.
    The connection-oriented service is based on the telephone system. To talk to someone, first pick up the phone, dial the number, call, and then stop. When using a connection-oriented service, you must first establish a connection, use a connection, and then release the connection. Essentially, a connection is like a pipe: the sender puts an object at one end of the pipe, and the receiver extracts the object in the same order at the other end. The characteristic is that the data sent and received is not only in the same order, but also in the same content.-Call similar

  • Unconnected Network Services

    You do not need to establish a connection before communication between two entities that have no connection to the network service. Connectionless network services can be classified into three types: Datagram, Confirmed Delivery, and Request reply ).
    The unconnected service is in the postal system mode. Each packet (letter) carries a complete destination address, and each packet is independent of other packets and transmitted through the route selected by the system. Normally, when two packets are sent to the same destination, they are first served. However, it is also possible that the first packet is delayed on the way, and the sent packet is received first. This situation is absolutely impossible in connection-oriented services.-Text Messages

Transmission Control Protocol (TCP)

Three-way handshake:

 

 

Three-time grip. PNG

The TCP process is complex, including the following content.

  • TCP Connection closed: After a TCP connection is established between the sender host and the target host and data transmission is completed, a packet marked with end 1 is sent to close the TCP connection, the buffer space occupied by the connection is also released.
  • TCP Reset: TCP allows a sudden disconnection during transmission.
  • TCP data sorting and confirmation *: the serial number and confirmation number are used during transmission to track data receipt.
  • TCP retransmission: During TCP transmission, if the recipient's host does not receive a confirmation reply to a data packet within the Retransmission timeout period, the sender's host considers the data packet to be lost, and send the packet to the receiver again.
  • TCP Delay confirmation: TCP does not always confirm the received data immediately. It allows the host to send its confirmation information to the recipient while receiving the data.
  • TCP Data Protection (verification): TCP is a reliable transmission protocol that provides verification and calculation to ensure data integrity during transmission.
User Datagram Protocol (UDP)

The full name of UDP is User datav Protocol, and the Chinese name is User Datagram Protocol. UDP provides a connectionless network service that provides unreliable and best-effort transmission of data transmitted in messages. This means that it does not guarantee the arrival of the datagram, nor does it ensure that the order of the transmitted packets is correct.
I initially had a question: "Since UDP is an unreliable network protocol, what is the value or necessity ?"
In some cases, UDP may become very useful. Because UDP has a speed advantage beyond the reach of TCP. Although various security protection functions are embedded in TCP, a large amount of system overhead will be occupied during actual execution, and the speed will undoubtedly be seriously affected. In contrast, UDP eliminates the information reliable transfer mechanism and transfers security and sorting functions to upper-layer applications, greatly reducing the execution time and ensuring the speed.

TCP and port number

Both TCP and UDP are IP-level transmission protocols and are the processing interfaces between the IP address and the upper layer. TCP and UDP port numbers are designed to distinguish the IP addresses of multiple applications running on a single device. Because multiple network applications may run on the same computer, the computer must ensure that the software applications on the target computer that receive data packets from the source host are correct, and the response can be sent to the correct application on the source host. This process is implemented by using the TCP or UDP port number.
-- Each application registers a port number on the NIC to distinguish the communication between applications on the same device.

In the TCP and UDP headers, there are "Source Port" and "Target Port" segments, which are mainly used to display identity identification information during sending and receiving. The combination of IP addresses and port numbers is called "socket ". TCP ports are complex and work in different ways than UDP ports. The UDP port operates UDP-based communication as a single message queue and network endpoint, and the end point of all TCP communication is a unique connection. Each TCP connection is uniquely identified by two endpoints. Because all TCP connections are uniquely identified by two pairs of IP addresses and TCP ports (each connected host has an address/Port Pair ), therefore, each TCP server port can provide shared access to multiple connections.
Let's take a look at IP packets and TCP/UDP packets.

 

 

Data Package .png
HTTP protocol

HyperText Transfer Protocol (HTTP) is the most widely used network Protocol on the Internet.
The http Protocol specifies the data transmission format between the client and the server.

  • Http advantages:

    Simple and fast:
    The http protocol is simple and the communication speed is fast;
    Flexibility:
    The http protocol allows transmission of any type of data;
    Transient connection:
    The http protocol limits that only one request can be processed for each connection. After the server responds to the client request, the connection is immediately disconnected. This method can save transmission time.

Http

Http defines many methods that correspond to different resource operations. The most common methods are GET and POST.
Eg: GET, POST, OPTIONS, HEAD, PUT, DELETE, TRACE, CONNECT, PATCH
Add: PUT
DELETE: DELETE
Change: POST
Query: GET
Because GET and POST can implement all the preceding operations, in actual development, the GET and POST methods are the most widely used. In addition, HEAD requests are frequently used;

  • GET

    After the request URL? Parameters are concatenated in the form of "parameter name" = "parameter value". Multiple parameters are separated;
    The essence of GET is to GET data from the server, which is more efficient. And GET requests can be cached.
    Note: The length of GET is limited. Different browsers have different length limits, generally between 2 ~ Between 8 K;

  • POST

    The essence of POST is to send data to the server and obtain the results processed by the server. The efficiency is not as high as that of GET. POST requests cannot be cached. After each refresh, the form must be submitted again.
    All parameters sent to the server are placed in the 'request body;
    Theoretically, there is no limit on the amount of data transmitted by POST.
    Note: All data involving user privacy (password/bank card number, etc ...) It must be passed in POST mode.

  • HEAD

    The HEAD method is usually used to obtain the file information of the remote server before downloading the file! Compared with GET requests, object data is not downloaded and only response header information is obtained!
    Generally, the HEAD method is used to inform users of the object to be downloaded in advance. The user determines whether to download the object! Therefore, the HEAD method is recommended to send a synchronization request!

Response Message

1xx: Information Response class, indicating that the request is received and processed continuously
2xx: Successful response class, indicating that the action is successfully received, understood, and accepted
3xx: redirect response class. To complete the specified action, you must accept further processing.
4xx: client error. The client request contains a syntax error or cannot be correctly executed.
5xx: A server error occurs. The server cannot correctly execute a correct request;
Detailed Description: Status Code

Introduction to SocketSocket
  • Socket originated in the early 1980s s and was first introduced by 4.1c bsd unix, so it is also called "BSD Socket or Berkeley Socket ". BSD Socket is a de facto Network Application Programming Interface Standard. Other programming languages often use interfaces similar to this set (programming interfaces written in C.
  • Socket can be used to realize data communication between different hosts on the network or between different objects on the same host. Therefore, Socket is now a set of common communication interfaces.
    There are two types: network Socket and local Socket.
How do two local processes communicate?
 
 
  • Memory Sharing (munmap());
  • Messages and queues;
  • Pipeline (anonymous Pipelinepipe()And named Pipelinemkfifo());
  • Semaphores (P VOperation );
  • RPC remote protocol control
  • Local Socket;
How do two processes communicate on the network?

Local inter-process communication (IPC) uses PID (enter ps-ef in the terminal to view the PID) to uniquely identify each other and then communicate with each other through shared memory and message queues; the two processes on the network determine the IP address and port number required for each other and communicate with each other through the transport layer (TCP/UDP) protocol;
This is the network Socket.
Socket can be understood as: Add a port to TCP/UDP (registered on the NIC, remember) to bind.

Comparison between network socket and local Socket
 
 
  • On the same device, if two processes need to communicate with each other, a process can be uniquely identified. In local process communication, a PID can be used to uniquely identify a process;
  • PID is only unique locally. The two processes in the network have a high chance of PID conflict. Obviously, this is not the case. What should I do?
    The IP address of the IP layer can uniquely identify the host, while the TCP protocol and port number can uniquely identify a process of the host. Therefore, you can use the IP address + protocol + port number to uniquely identify a process in the network.

Socket communication is a TCP/IP communication that determines the port number, or the difference between Socket communication and IP communication is that the port is determined, and the protocol is determined.

Use a chart:

 

 

Socket.png

The port is opened by both parties. In the TCP connection of the C/S (Client & Server) structure, we should not only note the S port (listened ), in fact, C also opens a port, while the C-end port is a dynamic port. When a TCP connection is established, the C-end port is determined after the three-way handshake, and one is opened dynamically, this port is not controlled by users/programmers.

Socket C-end writing steps

A classic step diagram of Socket C/S.

 

 

Objective-C
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 1. import header file # import <sys/socket. h> // socket related # import <netinet/in. h> // internet related # import <arpa/inet. h> // Address Resolution Protocol 2. socket (created) int socket (int, int, int);/** parameter first int: domain: Protocol domain, AF_INET (IPV4 network development) Second int: type: socket type, SOCK_STREAM (TCP)/SOCK_DGRAM (UDP, packet) Third int: protocol: IPPROTO_TCP, protocol. If you enter 0, you can automatically select the protocol return value socket based on the second parameter, if the value is greater than 0, the operation is successful */3. connection (connect to "server") connect (int, const struct sockaddr *, socklen_t)/** parameter 1> client socket 2> pointer to Data Structure sockaddr, this includes the "struct" Address of the destination port and IP address server. The C language does not have objects. 3> the struct Data Length returns 0 success/other error codes */4. write (send data) send (int, const void *, size_t, int) /** parameter 1> client socket 2> sending content address void * = id 3> sending content length 4> sending method flag. Generally, it is 0 and the return value is successful, returns the number of bytes sent, and SOCKET_ERROR */5 if the request fails. read (receive) recv (int, void *, size_t, int)/** parameter first int: created socket void *: Address of the received content size_t: the second int in length of the received content.: Mark 0 for receiving data. It is a blocking type. It waits for the length of data received by the server's data return value */6. close (int); int: the socket

 

 

Follow the above five steps to write a small demo of socket communication:

The written content has been put on my github;
At this time, no data is written to the server. How can I test it?
You can use: nc-lk port number to always listen to data on this port of the local computer.
Eg: nc-lk 6666;
Operation Procedure gif
1. Listen to port 6666
2. connettion;
3. Sendsocket; The server receivessocket;
4. server send: hello socket;

 

 

Procedure

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.