Socket principle and Programming basics

Source: Internet
Author: User
Tags file transfer protocol htons

First, Socket introduction socket is a way of process communication, that is, call this network library of some API functions to distribute in different host related processes between the data exchange. Several definitions: (1) IP address: that is, according to the TCP/IP protocol assigned to the local host network address, two processes to communicate, either process first to know the location of the communication, that is, the other side of the IP. (2) port number: Used to identify the local communication process, a local process in the communication will occupy a port number, different process port number is different, so before the communication must be assigned a port number that is not accessed. (3) Connection: Refers to a communication link between two processes. (4) Semi-related: The network with a ternary group can be globally unique flag a process: (Protocol, local address, local port number) such a ternary group, called a semi-correlation, it specifies each half of the connection. (4) Full correlation: A complete inter-network process communication needs to consist of two processes and can only use the same high-level protocol. That is, it is not possible to communicate at one end with the TCP protocol, and the other end with the UDP protocol. Therefore a complete inter-network communication requires a five-tuple to identify: (protocol, local address, local port number, remote address, remote port number) Such a five-tuple, called a Correlation (association), that is, two protocols of the same semi-correlation can be combined into a suitable correlation, or fully specified to form a connection. Second, client/server mode in TCP/IP network applications, the main mode of communication between the two processes is the client/server (Client/server, c/s) mode, that is, the customer sends the service request to the server, the server receives the request, provides the corresponding service. The client/server model is based on the following two points: (1) First, the cause of network is the network hardware and software resources, computing power and information is not equal, need to share, so as to create a host with a large number of resources to provide services, less resources of Customer request service This non-reciprocal role. (2) Second, the inter-network process communication is completely asynchronous, the process of communication between the two processes do not have a parent-child relationship, and do not share memory buffer, it is necessary to establish a mechanism for communication between the process of establishing a link between the two data exchange to provide synchronization, which is based on the client/server mode of TCP/IP. Server-side: The process is the first server to start, and according to the request to provide the appropriate services: (1) Open a communication channel and inform the local host, it is willing to a certain address on a port (such as the FTP port may be 21) to receive customer requests, (2) waiting for customer requests to reach the port ; (3) When a service request is received from a client, the request is processed and a response signal is sent. Receives a concurrent service request to activate a new process to handle this customer request (such as fork, exec in a UNIX system). The new process handles this customer request and does not need to respond to other requests. After the service is complete, close the communication with the customer for this new processLink, and terminates. (4) Return to step (2) and wait for another customer to request. (5) Shut down the Server client: (1) Open a communication channel and connect to a specific port on the host where the server is located, (2) Send a service request message to the server, wait and receive the answer, continue to make a request ... (3) Close the communication channel and terminate after the request is finished. From the process described above: (1) The role of the client and the server process is asymmetric, so the code is different. (2) The server process is typically started first. As long as the system is running, the service process persists until normal or forced termination. After introducing the basics, here are some API functions: Create socket ──socket () the application must first have a socket before using a socket, and the system calls the socket () to provide the application with the means to create the socket, which is called in the following format: Socket PASCAL Far socket (int af, int type, int protocol); The call receives three parameters: AF, type, protocol. Parameter AF specifies the area in which the communication occurs: Af_unix, Af_inet, Af_ns, and so on, while DOS, Windows only supports Af_inet, which is the internetwork zone. Therefore, the address family is the same as the protocol family. The parameter type describes the type of socket to be established. There are three kinds: (1) One is the TCP streaming socket (SOCK_STREAM) provides a connection-oriented, reliable data transmission service, no error, no duplication of sending, and in the order of sending received. Internal flow control to avoid data flow overrun, data is considered as a byte stream, no length limit. File Transfer Protocol (FTP) uses streaming sockets. (2) The second is the datagram Socket (SOCK_DGRAM) provides a non-connected service. Packets are sent in a separate package, without error-free guarantees, data may be lost or duplicated, and the order of reception is confusing. The Network File system (NFS) uses a datagram socket. (3) Three is the original socket (SOCK_RAW) that interface allows direct access to lower-level protocols such as IP, ICMP. Often used to verify a new protocol implementation or to access new devices that are configured in an existing service. The parameter protocol describes the specific protocol used by the socket, and if the caller does not want to specifically specify the protocol used, set to 0, using the default connection mode. Based on these three parameters, a socket is established and the corresponding resource is assigned to it, and an integer socket size is returned. Therefore, the socket () system call actually specifies the "protocol" element in the related five-tuple. Specify local address ──bind () when a socket is created with a socket (), there is a namespace (address family), but it is not named. Bind () Sets the socket address (including the local host address and local port toConnection to the created socket, assigning the name to the socket to specify local semi-correlation. Its invocation format is as follows: int PASCAL far bind (SOCKET s, const struct SOCKADDR FAR * name, int namelen); The parameter S is the socket descriptor (socket size) returned by the socket () call and not connected. The parameter name is the local address (first name) assigned to the socket s, and its length is variable, and the structure varies with the communication domain. Namelen indicates the length of the name. If no error occurs, bind () returns 0. Otherwise, return socket_error. Establish socket connection ──connect () and accept () These two system calls are used to complete a complete correlation establishment where connect () is used to establish the connection. The Accept () is used to cause the server to wait for the actual connection from a client process. The call format for connect () is as follows: int PASCAL far connect (SOCKET s, const struct SOCKADDR FAR * name, int namelen); The parameter S is the local socket descriptor to which the connection is to be established. The parameter name indicates a pointer to the address structure of the other socket. The length of the other socket address is explained by Namelen. If no error occurs, connect () returns 0. Otherwise the return value is Socket_error. In a connection-oriented protocol, this call causes the connection between the local system and the external system to actually be established. Because the address family is always included in the first two bytes of the socket address structure and is associated with a protocol family through the socket () call. So bind () and connect () do not require a protocol as a parameter. The call format for accept () is as follows: Socket PASCAL far accept (socket s, struct sockaddr far* addr, int far* addrlen); The parameter s is a local socket descriptor, which should be called before listen () before being used as a parameter to the accept () call. Addr A pointer to the client socket address structure that is used to receive the address of the connection entity. The exact format of the addr is determined by the address family established when the socket was created. Addrlen the length (in bytes) of the client-side socket address. If no error occurs, accept () returns a value of the socket type that represents the descriptor of the received socket. Otherwise the return value is Invalid_socket. Accept () is used for connection-oriented servers. Parameters addr and Addrlen store the client's address letterInterest. Before the call, the parameter addr points to an address structure with an initial value of NULL, while the initial value of Addrlen is 0, and after the call to accept (), the server waits for a client connection request from a socket numbered s, and the connection request is made by the client's connect () call. When a connection request arrives, the Accept () call places the first client socket address and length on the request connection queue into addr and Addrlen, and creates a new socket size that has the same characteristics as S. The new socket can be used to process server concurrent requests. Four sockets system calls, Sockets (), bind (), connect (), accept (), can complete a completely five-dollar related establishment. The socket () specifies the protocol element in a five-tuple, which is used in relation to whether it is a client or server, or whether it is connection-oriented. Bind () specifies a local two-dollar, local host address and port number in a five-tuple, and its usage is related to whether it is connection-oriented: Bind () is called on the server side, regardless of whether it is connection-oriented, or bind () is not called with connection-oriented, and can be done automatically via connect (). With no connection, the client must use BIND () to obtain a unique address. Listener Connection ──listen () This call is used to target the connection server, indicating that it is willing to receive connections. Listen () needs to be called before accept () with the following format: int PASCAL far Listen (SOCKET s, int backlog); The parameter s identifies a locally established, not yet connected socket size, and the server is willing to receive requests from it. The backlog represents the maximum length of the request connection queue and is used to limit the number of queued requests, currently allowing a maximum value of 5. If no error occurs, listen () returns 0. Otherwise it returns SOCKET_ERROR. Listen () can complete the required connection for socket s that have not called bind () during the call process and establish a backlog-length request connection queue. Calling Listen () is the third step in the four steps a server receives for a connection request. It allocates a stream socket in the calling socket () and calls bind () to the s assigned to a name, and must be called before accept (). Data transfer ──send () and recv () when a connection is established, it can be transferred. Common system calls have Send () and recv (). A send () call is used to send output data on a connected datagram or a stream socket specified by S, in the following format: int PASCAL far send (SOCKET s, const char far *buf, intLen, int flags); The parameter s is a connected local socket descriptor. The BUF points to a pointer to the buffer that holds the data, which is specified in length by Len. Flags specifies the mode of transmission control, such as whether to send out-of-band data. If no error occurs, send () returns the total number of bytes sent. Otherwise it returns SOCKET_ERROR. The recv () call is used to receive input data on the connected datagram or stream socket specified by S, in the following format: int PASCAL far recv (SOCKET s, char far *buf, int len, int flags); The parameter s is a connected socket descriptor. The BUF points to the pointer that receives the input data buffer, whose length is specified by Len. Flags specifies the mode of transmission control, such as whether to receive out-of-band data. If no error occurs, recv () returns the total number of bytes received. Returns 0 if the connection is closed. Otherwise it returns SOCKET_ERROR. The input/output multiplexing ──select () Select () call is used to detect the state of one or more sockets. For each socket, this call can request information about a read, write, or Error state. A collection of sockets that request a given State is indicated by a fd_set structure. On return, this structure is updated to reflect the subset of sockets that meet certain criteria, while the Select () call returns the number of sockets that meet the criteria, with the following invocation format: int PASCAL far Select (int Nfds, fd_set FAR * Readfds , Fd_set FAR * Writefds, Fd_set FAR * exceptfds, const struct TIMEVAL FAR * timeout); The parameter Nfds indicates the value of the checked socket descriptor, which is generally ignored. The Readfds parameter points to a pointer to a collection of socket descriptors to be read-tested, which the caller wants to read from. The Writefds parameter points to a pointer to the set of socket descriptors to be write-detected. Exceptfds a pointer to a collection of socket descriptors to detect if an error occurred. Timeout points to the maximum time the Select () function waits, or a blocking operation if set to null. Select () returns the total number of socket descriptors that are prepared in the FD_SET structure, or returns SOCKET_ERROR if an error occurs. Closes the socket ──closesocket () closesocket () closes the socket S and releases the resources assigned to the socket, and if s involves an open TCP connection, the connection is freed. CloThe invocation format of Sesocket () is as follows: BOOL PASCAL far closesocket (SOCKET s); parameter s the socket descriptor to be closed. If no error occurs, closesocket () returns 0. Otherwise the return value is Socket_error. The above is the socket API some common API functions, the following is a section of code://Client code: #include #include #pragma comment (lib, "Ws2_32.lib") int main () {int err; WORD versionrequired; Wsadata Wsadata; Versionrequired=makeword (a); Err=wsastartup (versionrequired,&wsadata);//The version information of the Protocol Library if (!err) {printf ("The client nested word has been opened!\n");} else {printf (" The client's nested word open failed!\n "); Return 0;//End} SOCKET clientsocket=socket (af_inet,sock_stream,0); Sockaddr_in clientsock_in; Clientsock_in.sin_addr. S_un. S_ADDR=INET_ADDR ("127.0.0.1"); Clientsock_in.sin_family=af_inet; Clientsock_in.sin_port=htons (6000); Bind (Clientsocket, (sockaddr*) &clientsock_in,strlen (sockaddr));//Note The third parameter//listen (clientsocket,5); Connect (Clientsocket, (sockaddr*) &clientsock_in,sizeof (sockaddr));//Start connecting char receivebuf[100]; Recv (clientsocket,receivebuf,101,0); printf ("%s\n", receivebuf); Send (Clientsocket, "Hello,this is the client", strlen ("Hello,this is Client") +1,0); Closesocket (Clientsocket); WSACleanup (); return 0;} /////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////Server-side code: #include #include #pragma comment (lib, "Ws2_32.lib") int main () {//create socket word myversionrequest; Wsadata Wsadata; Myversionrequest=makeword (a); int err; Err=wsastartup (Myversionrequest,&wsadata); if (!err) {printf ("open socket \ n");} else {//further bind socket printf ("The nested word is not open!"); return 0;} Socket Sersocket=socket (af_inet,sock_stream,0);//Create an identifiable socket//need to bind the parameters sockaddr_in addr; Addr.sin_family=af_inet; Addr.sin_addr. S_un. S_addr=htonl (Inaddr_any);//IP address addr.sin_port=htons (6000);//Bind Port bind (Sersocket, (sockaddr*) &addr,sizeof ( SOCKADDR));//Bind complete listen (sersocket,5);//The second parameter represents the maximum number of connections that can be received/////////////////////////////////////////////////// Start the monitoring////////////////////////////////////////////////////////////////////////// Sockaddr_in Clientsocket; int len=sizeof (SOCKADDR); while (1) {SOCKET serconn=accept (Sersocket, (sockaddr*) &clientsocket,&len);//If this is not accept but conection. Will constantly listen to Char sendbuf[100]; sprintf (SendBuf, "Welcome%s to Bejing", Inet_ntoa (CLIENTSOCKET.SIN_ADDR)),//find the corresponding IP andThis line of words prints to There send (Serconn,sendbuf,strlen (SENDBUF) +1,0); Char receivebuf[100];//receive recv (Serconn,receivebuf,strlen (RECEIVEBUF) +1,0); printf ("%s\n", receivebuf); Closesocket (serconn);//close WSACleanup ();//release resource operation} return 0;}

Socket principle and programming basics

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.