TCP/IP protocol family anatomy && sockets for IOS

Source: Internet
Author: User
Tags ack

Brief introduction

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

In this article, I list the common protocols in the TCP/IP family, the main character today is the Transport layer protocol.

The Transport layer (Transport layer) is the most important and critical layer of the OSI (seven-tier model), which is responsible for the overall data transfer and control of the first layer, the Transport layer provides end-to-end (application will register a port number on the network card) Exchange data mechanism, check the grouping number and sequence. The transport layer provides reliable transmission service to three layers, such as the conversation layer, and provides reliable destination site information to the network layer.

Protocols in the Transport layer
    The
    • Transport layer provides session and datagram communication services for the application tier. The
    • Transport Layer assumes the responsibility of the OSI Transport layer. The core protocol of the
    • Transport layer is TCP and UDP.

      TCP provides a one-to-one, connection-oriented, reliable communication service. TCP establishes a connection, sorts and confirms the packets sent, and recovers packets that were lost during transmission. Unlike TCP, UDP provides one-to-one or one-to-many, non-connected, unreliable communication services.
      either TCP/IP or the OSI reference Model, the lower layer of any adjacent two tiers is the service provider, and the upper layer is the service caller. The services provided on the lower level are divided into two categories: connection-oriented and no-connection services.

    • for Connected network services

      Connection-oriented network services, also known as virtual circuit (virtual circuit) services, with network connection setup, data transfer, and network connection release Three stages. is the sequential transmission of reliable packet grouping, suitable for the specified object, long message, session-type transmission requirements. The
      connection-oriented service is in the Telephony system mode. To talk to someone, first pick up the phone, dial the number, call, and then hang up. Also when using a connection-oriented service, the user first establishes a connection, uses the connection, and then releases the connection. A connection is essentially a pipe: the sender puts an object at one end of the pipe, and the receiver takes the object in the same order at the other end, with the characteristic that the data sent and received are not only consistent in order but also of the same content. – Similar calls

    • No connected Network Service

      Communication between two entities that have no connection to the Network service does not require a good one connection to be established beforehand. There are 3 types of non-connected network services: Datagram (Datagram), acknowledgment of delivery (confirmed Delivery) and request for answer (requests reply). The
      No connection service is in the postal system mode. Each message (letter) has a complete destination address, and each message is independent of other messages and is routed by the system-selected route. Under normal circumstances, when two messages are sent to the same destination, first comes first. However, it is also possible that the first message is delayed on the way, but the message is received first, which is absolutely not possible in a connection-oriented service. – Similar texting

Transmission Control Protocol (TCP)
    1. TCP full name is transmission Control Protocol, the Chinese name is the transmission protocol, it can provide a reliable, connection-oriented network data delivery service. The Transmission Control protocol primarily includes the following tasks and features:
    2. Ensure the successful delivery of IP datagrams.
      • Fragment and reorganize large chunks of data sent by the program.
      • Ensure that segmented data is correctly sorted and delivered sequentially.
      • The integrity of the transmitted data is checked by calculating the checksum.
      • The positive message is sent based on whether the data was received successfully. By using selective acknowledgments, negative acknowledgments are also sent for data that is not received.
        Provides the preferred transfer method for the use of reliable, session-based data transfer programs, such as client/server databases and e-mail programs.
    3. How TCP Works
      TCP connection establishment process is also known as TCP three-time handshake ;

      • First, the sending host initiates a synchronous (SYN) request to the receiving host to establish a connection;
      • The receiving host responds to a synchronization/acknowledgment (Syn/ack) response to the sending host after receiving the request;
      • When the sender host receives this package and then sends an acknowledgment (ACK) to the receiving host, the TCP connection is successfully established.
        Once the initial three-time handshake is complete, the segments are sent and confirmed sequentially between the sending and receiving hosts. Before closing the connection, TCP uses a similar handshake process to verify that two hosts have completed sending and receiving all of the data.
        Three handshake is completed and the client and server begin to transfer data.

Three-time handshake:

Three-time handshake. png

The TCP work process is complex and includes the following content.

    • TCP connection shutdown: After the sending host and destination host establish a TCP connection and complete the data transfer, a packet with the end tag of 1 is sent to close the TCP connection and free the buffer space occupied by the connection.
    • TCP Reset: TCP allows the connection to be interrupted abruptly during transmission.
    • TCP Data Ordering and acknowledgment *: Use serial numbers and confirmation numbers to track the reception of data during transmission.
    • TCP retransmission: During the transmission of TCP, if the recipient host does not receive a confirmation reply to a packet within the retransmission timeout period, the sending host considers the packet to be lost and sends the packet again to the receiver.
    • TCP delay Acknowledgement: TCP does not always acknowledge the data immediately after it is received, it allows the host to send its own acknowledgement to each other while receiving the data.
    • TCP Data Protection (checksum): TCP is a reliable transmission protocol that provides checksum computation to achieve the integrity of the data during transmission.
User Datagram Protocol (UDP)

The UDP full name is User Datagram Protocol, the Chinese name is the Subscriber datagram protocol. UDP provides a non-connected network service that provides unreliable, maximum-effort transmission of data that is transmitted in the message. This means that it does not guarantee the arrival of the datagram, nor does it guarantee the correct order of the packets being transmitted.
I initially had a question: "Since UDP is an unreliable network protocol, what use or necessity is there?" ”
In some cases, UDP may become very useful. Because UDP has the speed advantage that TCP can not catch. Although a variety of security features are embedded in TCP, there is a significant amount of overhead involved in the actual execution of the system, which undoubtedly makes the speed seriously affected. In view of the elimination of the information reliable transmission mechanism, the security and sequencing functions are transferred to the upper application to complete, which greatly reduces the execution time and makes the speed guaranteed.

TCP and Port numbers

Both TCP and UDP are IP-level transport protocols, which are the processing interfaces between IP and the upper layer. The TCP and UDP port numbers are designed to differentiate the IP addresses of multiple applications running on a single device. Because more than one network application may run on the same computer, the computer needs to ensure that the software application that receives the source host packet on the target computer is correct and that the response can be sent to the proper application on the source host. This process is accomplished by using TCP or UDP port numbers.
-that is, each application registers a port number on the NIC to differentiate between applications on the same device

In the TCP and UDP header sections, there are "source port" and "Destination port" segments that are used primarily to display identification information during the sending and receiving process. The combination of IP address and port number is called "socket". TCP ports are more complex and work differently than UDP ports. UDP ports operate on UDP-based communication as a single message queue and as a network endpoint, and all TCP traffic endpoints are unique connections. Each TCP connection is uniquely identified by a two endpoint. Because all TCP connections are uniquely identified by two IP addresses and TCP ports (each host has an address/port pair), each TCP server port can provide shared access to multiple connections
Take a look at IP packets and TCP/UDP packets

Packet. PNG

HTTP protocol

Hypertext Transfer Protocol (Http,hypertext Transfer Protocol) is one of the most widely used network protocols on the Internet.
The HTTP protocol specifies the format of data transfer between the client and the server.

    • HTTP Advantages:

      Simple and quick:
      HTTP protocol is simple, communication speed is fast;
      Flexible:
      The HTTP protocol allows the transmission of arbitrary types of data;
      Short connections:
      The HTTP protocol restricts each connection to only one request, and the server immediately disconnects after responding to a request from the client. This method can save transmission time.

Use of the HTTP protocol
  1. Request: The client asks for data from the server. The
    HTTP protocol stipulates that a complete HTTP request contains ' request line ', ' request header ', ' request body ' three parts;  

     

    • Request line: Contains the request method, request resource path, HTTP protocol version. Get/resources/images/http/1.1″
    • Request Header: Contains information about the client's environment description, the host address requested by the client, and so on.

      Accept:text/html (the data type that the client can receive)
      ACCEPT-LANGUAGE:ZH-CN (client's locale)
      Accept-encoding:gzip (Customer Supported data compression format)
      Host:m.baidu.com (the server host address the client wants to access)
      user-agent:mozilla/5.0 (Macintosh;intel Mac OS X10.10 rv:37.0) gecko/20100101firefox/37.0 (client-type, client-side software environment)

    • request body: Specific data that the client sends to the server, such as files/pictures, etc.
  2. Response: The server returns the data the client wants
    The HTTP protocol states that a complete HTTP response contains a ' status line ', ' response header ', ' entity content ' three parts;

    • Status line: Contains the HTTP protocol version, status, status English name.
      "http/1.1 OK"
    • Response header: Contains a description of the server and a description of the returned data.

      Content-encoding:gzip (data compression format supported by the server) content-length:1528 (the length of the returned data)
      Content-type:application/xhtml+xml; (type of return data)
      DATE:MON,15JUN201509:06:46GMT (response time) Server:apache (server type)

    • Entity content: The specific data that the server returns to the client (picture/html/file ...).
  3. Send HTTP request
    In iOS development, there are a number of scenarios for sending HTTP requests, often in the following ways:

    • Apple native:

      Nsurlconnection:
      A scheme of simple usage and ancient classics.
      Nsurlsession:
      IOS7 later introduced the technology, function nsurlconnection more powerful.
      Cfnetwork:nsurl the bottom, pure C language, generally do not use.

    • Third-party frameworks:
      Afnetworking (OC); Alamofire (Swift);
HTTP method

The HTTP protocol defines a number of methods that correspond to different resource operations, the most common of which are the get and post methods.
Eg:get, POST, OPTIONS, HEAD, PUT, DELETE, TRACE, CONNECT, PATCH
Add: PUT
Delete: Delete
Change: POST
Check: GET
Because get and post can do all of the above, so in real-world development, get and post methods are the most widely used, in addition to the head request usage frequency is also relatively high;

    • GET

      After the request URL in the form of a to follow the parameters issued to the server, the parameters are "parameter name" = "parameter value" in the form of splicing, multiple parameters are separated by &;
      The essence of get is that it is more efficient to get data from the server. And a GET request can be cached.
      Note: The length of get is limited, and different browsers have different length limits, generally between 2~8k;

    • POST

      The essence of post is to send data to the server, but also to get the result after the server processing, the efficiency is not as Get.post request can not be cached, after each refresh will need to resubmit the form.
      The parameters sent to the server are all placed in the ' request body ';
      In theory, there is no limit to the amount of data that post transmits.
      Note: All data related to user's privacy (password/bank card number etc...) Must be delivered by post.

    • HEAD

      The head method is usually used to get the file information of the remote server before downloading the file! File data is not downloaded and only the response header information is obtained, compared to a GET request!
      In general, the purpose of using the head method is to tell the user in advance to download the file information, the user determines whether to download the file! So, head method, it is best to send a sync request!

Response message

1XX: Information response class, which indicates receipt of request and continues processing
2XX: Handle the successful response class, indicating that the action was successfully received, understood, and accepted
3XX: Redirect Response class, must accept further processing in order to complete the specified action
4XX: Client error, client request contains syntax error or is not executed correctly
5XX: Server error, the servers do not correctly execute a correct request;
Detailed Description: Status code

Socketsocket Introduction
    • Socket originated in the early the 1980s, the earliest introduced by 4.1c BSD UNIX, so also known as "BSD socket or Berkeley socket." BSD sockets are the de facto programming interface standard for Web applications, and other programming languages often use similar interfaces to this set of programming interfaces written in C.
    • Using a Socket enables data communication between different hosts on the network or between different objects on the same host. So, now the Socket is already a collection of generic communication interfaces.
      Large types can be divided into network sockets and local sockets two kinds.
How are the two processes on the ground communicating?
  • Memory Sharing ( munmap() );
  • Messages and queues;
  • Pipelines (anonymous pipes pipe() and Named Pipes mkfifo() );
  • Signal Volume ( P V operation);
  • RPC Remote Protocol Control
  • Local sockets;
How does the two processes on the network communicate?

Local interprocess communication (IPC) through the PID (input ps-ef in the terminal can see the PID) can uniquely identify each other, and then through the shared memory, Message Queuing to pass, the network of two processes to identify each other need IP and port number, through the Transport Layer (TCP/UDP) protocol to communicate;
This is the network Socket.
socket可以理解为:在TCP/UDP 加一个端口(在网卡注册的,还记得吧)绑定。

Network socket vs. local socket
  • On the same device, two processes if you need to communicate the most basic premise can be able to uniquely identify a process, in the local process communication can use PID to uniquely identify a process;
  • PID only in the local only, the network of two process PID collision probability is very large, at this time obviously not, how to do?
    The IP address of the IP layer can uniquely identify the host, and the TCP layer protocol and port number can uniquely indicate a process for the host, so the IP address + protocol + port number can be used to uniquely identify a process in the network.

Socket communication is a kind of TCP/IP communication that determines the port number, or the difference between socket communication and IP communication is the port determination and the protocol determination.

Use a chart to reach:

Socket.png

The opening of the port is two sides, in the C/s (CLIENT&&SERVER) structure of the TCP connection not only to notice the port of S (listening), in fact, C also opened a port, and the C port is a dynamic port, when the TCP connection is established, The port on the C end is determined after the three handshake, and is dynamically opened, which is not controlled by the user/programmer.

Socket C-terminal writing steps
    1. Creating a Client socket
    2. Create a server socket
    3. Connect to the server (socket programming)
    4. Sending data to the server
    5. Data returned by the receiving server
    6. Close Socket:close (Socketnumber)

A classic socket c/S step diagram.

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 related2. socket(create ) int socket(int, int, int);     /**ParametersFirst Int:domain: protocol domain, AF_INET (IPV4 's network development)second Int:type:Socket type, Sock_stream (TCP)/sock_dgram (UDP, message)The third Int:protocol:IPPROTO_TCP, the protocol, if input 0, can be automatically selected according to the second parameterreturn valuesocket, if > 0 means success     */3. Connection (connect to "server" ) Connect(int, const struct sockaddr *, socklen_t )    /**Parameters1> Client Socket2> Pointer to the data structure sockaddr, which includes the destination port and IP addressThe "struct" address of the server, the C language has no objects3> Structure Data lengthreturn value0 Successes/other error codes     */4. Write(send data ) send(int, const void *, size_t, int )    /**Parameters1> Client Socket2> Send content address void * = = ID3> Send Content length4> send way flag, typically 0return valueIf successful, returns the number of bytes sent, and the failure returns SOCKET_ERROR      */5. Read (receive ) recv(int, void *, size_t, int)     /**ParametersFirst int: socket createdvoid *: Address of received contentsize_t: The length of the received contentThe second int.: The token 0 that receives the data is blocked, waiting for the server's datareturn valuelength of data received     */6. close Close(int); int: is the socket created

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

Well written has been put on my github;
There is no write server at this time, how to test?
Available: Nc-lk port number: Always listen for data on this port on the local computer.
Eg:nc-lk 6666;
Operation Steps gif
1, monitoring 6666 ports
2, Connettion;
3, send socket ; the server received socket ;
4, the service end Send:hello socket;

Operation steps. gifs End socket Communication steps
      1. Provide some services
      2. Bind this service to its own IP address, port
      3. Listen for any TCP requests to this ip+ port
      4. Accept/Deny establishing this TCP connection
      5. Write
      6. Disconnecting a TCP connection
      7. Ask--One-click Programmer to answer the question artifact, one-man service for cattle, developer Programming Essentials official website: www.wenaaa.com

        QQ group 290551701 gathers a lot of Internet elite, technical director, architect, project Manager! Open source technology research, Welcome to the industry, Daniel and beginners are interested in engaging in IT industry personnel to enter!

TCP/IP protocol family anatomy && sockets for IOS

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.