Socket network programming, socket

Source: Internet
Author: User
Tags sendmsg

Socket network programming, socket
Socket network programming network communication three elements:

  • IP Address [host name]
    • Identifier of the device in the Network
    • Local loopback address: 127.0.0.1 Host Name: localhost
  • Port Number
    • The logical address used to identify the process.
    • Valid port: 0 ~ 65535
    • 0 ~ 1024 is used or reserved by the system. Do not use port 1024 during development.
  • Transmission Protocol [communication rules]
    • TCP
    • UDP
Common network protocols
Protocol Port Description
HTTP 80 Hypertext Transfer Protocol
HTTPS 443 HTTP + SSL, HTTP Security Edition
FTP 990 File Transfer
POP3 110 Email Protocol
SMTP 25 Simple Mail Transfer Protocol
Telnet 23 Remote Terminal Protocol
Network Reference Model

TCP & UDPUDP (User datasync Protocol User Datagram)
  • Send the message without confirming whether the recipient has received the message.
  • Encapsulate data and source and target data into data packets without establishing a connection
  • The size of each datagram is limited64 kWithin
  • Because no connection is required, the Protocol is not reliable,Fast transmission speed
TCP (Transmission Control Protocol)
  • Establish a connection to form a data transmission channel
  • Transfer big data in the connection (Unlimited data size),
  • The three-way handshake is a reliable protocol for Secure delivery.
  • Connection is required, so the efficiency is relatively low.
Explanation on Socket Baidu encyclopedia
  • The original meaning of Socket is "hole" or "Socket ". As the process Communication Mechanism of bsd unix, take the latter meaning. It is also called "socket". It is used to describe the IP address and port and is a communication chain handle. Hosts on the Internet generally run multiple service software and provide several services at the same time. Each service opens a Socket and binds it to a port. Different ports correspond to different services. Socket is like a porous Socket, just as it was originally intended. A host is like a room with various sockets. Each socket has a serial number. Some sockets provide 220 v ac, some provide 110 v ac, and some provide cable TV programs. The customer software inserts the plug into a socket with different numbers to obtain different services.
Functions of Socket
  • Socket is a mechanism provided for network services.
    • In Unix, the network is both Socket and not limited to TCP/UDP.
    • Socket can be used for custom protocols
  • Both ends of the communication are Socket
  • Network Communication is actually the communication between sockets.
  • Data is transmitted through IO between two sockets
Socket Communication

Scoket Development
  • Prepare before development-import header files

    #import <sys/socket.h>

    #import <netinet/in.h>

    #import <arpa/inet.h>
  • Function Description

    1. scoket Functions

    • Function prototype:
      Int socket (int domain, int type, int protocol );
    • Parameter description
      • Domain: the Protocol domain, also known as the protocol family ). Common protocol families include AF_INET, AF_INET6, AF_LOCAL (or AF_UNIX, Unix Socket), and AF_ROUTE. The protocol family determines the socket address type and must use the corresponding address in the communication. For example, AF_INET decides to use ipv4 address (32-bit) and port number (16-bit) AF_UNIX decides to use an absolute path name as the address.
      • Type: Specifies the Socket type. Common socket types include SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_PACKET, and SOCK_SEQPACKET. Stream Socket (SOCK_STREAM) is a connection-oriented Socket for connection-oriented TCP Service applications. A datagram Socket (SOCK_DGRAM) is a connectionless Socket that corresponds to a connectionless UDP Service Application.
      • Protocol: Specify the protocol. Common protocols include IPPROTO_TCP, IPPROTO_UDP, IPPROTO_SCTP, and IPPROTO_TIPC, which correspond to TCP, UDP, STCP, and TIPC respectively.
        Note: type and protocol cannot be combined at will, for example, SOCK_STREAM cannot be combined with IPPROTO_UDP. When the third parameter is 0, the default Protocol corresponding to the second parameter type is automatically selected.
    • Return Value
      • If the call is successful, the descriptor of the newly created socket is returned. If the call fails, INVALID_SOCKET is returned (-1 is returned if the call fails in Linux ). The socket descriptor is an integer value.
    • int clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    2. connect Function

    • Function prototype: int pascal far connect (SOCKET s, const struct sockaddr FAR * name, int namelen );
    • Parameter description
      • S: identifies an unconnected socket
      • Name: pointer to the sockaddr struct to connect to the socket

        struct sockaddr_in serverAddr;
        serverAddr.sin_family = AF_INET;
        serverAddr.sin_port = htons(12345);
        serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
      • Namelen: the length of the sockaddr struct in bytes.
    • Return Value
      • If the call succeeds, 0 is returned. If the call fails,-1 is returned. The error cause is stored in errno.
    • int connResult = connect(clientSocket, (const struct sockaddr *)&serverAddr, sizeof(serverAddr));

      Note: in C language development, a pointer to a data structure is often passed, and the length of the data structure must be specified.

    3. send Function

    • Function prototype: int send (SOCKET s, const char * buf, int len, int flags );
    • Parameter description
      • SOCKET s: the sender socket descriptor, the client SOCKET
      • Const char * buf: the buffer (the data to be sent) of the data to be sent by the application, and the sending content address.
      • Int len: number of bytes to be sent
      • Int flags: The identifier of the sending method, which is usually set to 0.
    • Return Value
      • If the request succeeds, the number of sent bytes is returned. If the request fails, SOCKET_ERROR is returned.
    • NSString *sendMsg = @"Hello";


      ssize_t sendLen = send(clientSocket, sendMsg.UTF8String, strlen(sendMsg.UTF8String), 0);

      The execution process of the send function for Synchronous Socket is as follows:

      • When this function is called, send first compares the length of the data to be sent len with the length of the sending buffer (different from buf) of socket s. If len is greater than the length of the sending buffer of s, the function returns SOCKET_ERROR. If len is less than or equal to the length of the s sending buffer, send first checks whether the protocol is sending data in the s sending Buffer:

      • A. if the data is being sent, wait for the Protocol to finish sending the data.
      • B. If data in the buffer of sending s is not started, send will compare the remaining space and len size of the sending buffer of s:

      • If len is larger than the remaining space in the sending buffer (not enough space is placed in the remaining sending buffer), send waits until the Protocol finishes sending data in the s sending buffer;
      • If len is smaller than the remaining space in the sending buffer, it only copies the data in the buf to the remaining space in the sending buffer. (when the send function returns, it does not mean that the send function transfers the data in the s buffer (buf) to the other end of the connection, it is transmitted through the Protocol. send only copies the data in the buf to the rest of the sending buffer space of s ).
      • If the send function successfully copies the data, the actual number of bytes of copy is returned. If an error occurs when sending the copy data, the send function returns SOCKET_ERROR. If the send function breaks the network while waiting for the Protocol to send data, then the send function also returns SOCKET_ERROR.

        Note that the send function successfully copies the data in the buf to the remaining space of the s sending buffer and returns the data. However, the data is not necessarily uploaded to the other end of the connection immediately. If a network error occurs during subsequent transmission, the next Socket function will return SOCKET_ERROR. (each Socket function except send must wait for the data in the sending buffer of the Socket to be transmitted by the protocol before execution. If a network error occurs while waiting, then the Socket function returns SOCKET_ERROR ).

    4. recv Function

    • Function prototype: int recv (SOCKET s, char * buf, int len, int flags );
    • Parameter description
      • SOCKET s: the sender socket descriptor, the client SOCKET
      • Const char * buf: the buffer where the application stores the received data
      • Int len: actual buf Length
      • Int flags: The identifier of the receiving method. 0 indicates blocking. You must wait for the server to return data to 0.
    • Return Value
      • If yes, the number of received bytes is returned.
    • Uint8_t buffer [1024]; // prepare the space

      ssize_t recvLen = recv(clientSocket, buffer, sizeof(buffer), 0);

      The execution process of the recv function for Synchronous Socket is as follows:
      When the recv function is called, The recv waits for the data in the sending buffer of s to be sent by the Protocol:

    • A. If a network error occurs when the Protocol sends data in the sending buffer of s, the recv function returns SOCKET_ERROR;

    • B. If data in the sending buffer of s is successfully sent by the Protocol or there is no data, recv first checks the receiving buffer of socket s:
    • If there is no data in the s receiving buffer or the Protocol is receiving data, the recv waits until the Protocol receives the data. When the Protocol receives the data, the recv function copies the data in the s receiving buffer to the buf (note that the data received by the protocol may be larger than the length of the buf, in this case, you need to call the recv function several times to copy the data in the s receiving buffer. The recv function only copies the data, and the protocol is used to actually receive the data.) The recv function returns the actual number of bytes of the copy.
      If a recv error occurs during copy, SOCKET_ERROR is returned. If the recv function is interrupted while waiting for the Protocol to receive data, 0 is returned.

    5. close Function

    • Function prototype: int close (SOCKET s)
    • Parameter description
      • SOCKET s: the sender socket descriptor, the client SOCKET
    • Return Value
      • ???
    • close(clientSocket);

      Glossary:
      -Persistent connection: keep chatting when connected! It is usually used for QQ and instant messaging, with high efficiency!
      -Short connection: communication is performed once and the connection is closed immediately. The next connection is established, which is inefficient!

  • Socket development-Netcat

    $ Nc-lk 12345

    Netcat: a tool kit for debugging and checking networks on a terminal. It can be used to create TCP/IP connections.

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.