Socket Socket TCP API

Source: Internet
Author: User
Tags htons

Socket socket TCP Apisocket concept
    • Socket, also known as "socket", is a network of interprocess communication data channel of an endpoint, or called a handle. IP address + port number you can uniquely identify a socket.
    • The TCP/IP protocol family includes the transport layer (TCP/UDP), the network layer (ICMP/IP/IGMP), and the link layer (ARP/RARP). The application layer typically uses the socket address, which is the IP address + port number, to determine the peer of the communication. And socket is the TCP/IP protocol family and application layer between the interface layer, can be said to the upper layer provides a TCP/IP protocol family package, do not care about the lower level of implementation.
    • Applications typically use higher-level protocol libraries to program, and sockets are more categorized in the underlying driver programming. But it's always good to be familiar with sockets.
Socket address Structure
  • IP address + port number can uniquely determine a socket socket address, namedsockaddr_inInnetinet/in.hheader file, as defined below.
    struct in_addr{in_addr_t s_addr;};  struct sockaddr_in{uint8_t Sin_len;  sa_family_t sin_family;  in_port_t Sin_port;  struct IN_ADDR sin_addr; Char Sin_zero (0);};  
  • in_addr_t  in_port_t in netinet/in.h
  • in_addr_t is generally defined as uint32_t , in_port_t is generally defined as uint16_t
  • sa_family_t in sys/socket.h
  • uint8_t etc in sys/types.h
  • sin_addris the sin_port 32-bit IP address and port number stored in the network byte order
  • There are many types of socket addresses, in order to be able to use the socket API in the form of a pointer, you need to convert to a universal socket address sockaddr , generally forced type conversion.
Socket basic TCP API
  • Correlation functions defined sys/socket.h in the socket function
  • The socket function is used to create a socket.
    int socket(int family, int type, int protocal);
  • family is usually set to af_inet" Af_inet6 , respectively, represents the IPV4/6 protocol.
  • type is usually set to sock_stream  sock_dgram  sock_raw , respectively, represents the byte stream (TCP), datagram (UDP), raw socket.
  • Protocal represents the protocol family, and IPPROTO_TCP‘ ipproto_udp ' is usually set to 0.
  • The return value represents a non-negative socket descriptor
Connect function
  • Used to establish a connection
    int connect(int sockfd, const struct sockaddr *servaddr, int addrlen);
  • The TCP client uses the Connect function to establish a connection to the server side
  • This function fires the three handshake connection process for TCP until the link is established successfully or the error is returned
  • Each socket can only be called once, and after an error, you must close the current socket and call the socket again, connect
  • The function parameters are the socket descriptor, the universal socket address pointer, and its structure size.
Bind function
    • Bind binds the IP address and port to the socket descriptor
      int bind(int sockfd, const struct sockadddr *myaddr, int addrlen);
    • If the sin_addr.s_addr is set to Inaddr_any and the host has multiple network interfaces, you can accept the user connect on multiple network interfaces
Listen function
    • Listem converts a socket that does not call the Connect function to a passive listener socket
      int listen(int sockfd, int backlog);
    • The backlog specifies the maximum number of pending connections
Accept function
  • The kernel maintains an incomplete connection queue that is in the handshake connection phase for any of the listening sockets, and the connection queue is completed
  • Accept a listener socket descriptor each time it returns a connected socket descriptor in a connected queue
  • The socket address and address length of the connected socket are stored in the memory pointed to by CLIADDR and Addrlen. If you use two zero calls, you cannot get information such as the address and port represented by the client's connected sockets.
  • Close is expected for each completed connection, or the socket descriptor may be exhausted
    int accept(int sockfd, struct sockaddr *cliaddr, int *addrlen)
Close function
    • The default behavior of the close one TCP socket is to return the socket after it is marked as closed. But it triggered four wave-waving processes.
      int close(int sockfd);
Transferring data
    • A buffer is usually required and then sent using the recv, send function
    • Read and write are also available on the *nix system
      int recv(int sockfd, void *buf, size_t len, int flags);int send(int sockfd, const void *buf, size_t len, int flags);
TCP Communication client and server-side client processes
    • Connect to a server with connect and start transferring data
Server-side processes
    • You need to bind the network interface (BIND) First, then enter the listening state (listen), and finally take out a connected socket from the queue, that is, obtain a new connection (accept), and then start transferring data
The source code is as follows:
    • Server-side
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h>int    Main () {struct sockaddr_in local;    int s;    int SL;    int RC;    Char buf[1000];    local.sin_family = af_inet;    Local.sin_port = htons (7500);    LOCAL.SIN_ADDR.S_ADDR = htonl (Inaddr_any);    s = socket (af_inet, sock_stream, 0);        if (s < 0) {perror ("Socket call failed");    Exit (1);    rc = bind (s, struct sockaddr *) &local, sizeof (local));        if (RC < 0) {perror ("bind call failed");    Exit (1);    rc = Listen (s, 5);        if (RC < 0) {perror ("Listen call failed");    Exit (1);    } SL = Accept (s, null, NULL);        if (SL < 0) {perror ("Accept call failed");    Exit (1);    rc = recv (SL, buf, 10, 0);        if (RC < 0) {perror ("recv call failed");    Exit (1);    } printf ("%s\n", buf);    rc = Send (SL, "good", 10, 0);        if (RC < 0) {perror ("Send call failed"); EXIT (1); } exit (0);}
    • client
 #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h># Include<arpa/inet.h> #include <stdio.h>int main () {struct sockaddr_in peer; int s; int RC; Char buf[100]; peer.sin_family = af_inet; Peer.sin_port = htons (7500); PEER.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1"); s = socket (af_inet, sock_stream, 0); if (s < 0) {perror ("Socket call failed"); Exit (1); rc = Connect (s, (struct sockaddr *) &peer, sizeof (peer)); if (RC) {perror ("Connect call failed"); Exit (1); rc = Send (S, "Hello", 10, 0); if (RC <= 0) {perror ("Send call failed"); Exit (1); rc = recv (S, buf, 10, 0); if (RC <= 0) {perror ("recv call failed"); } else printf ("%s\n", buf); Exit (0);} 

 
 

Reprint please specify FOCUSTC, blog address for HTTP://BLOG.CSDN.NET/CAOZHK, the original link for Click Open

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.