Linux-socket TCP Client Server programming model and code explanation

Source: Internet
Author: User
Tags htons

The previous article introduced the TCP/IP protocol, the socket communication process and the various functions involved: socket simple Understanding this article will specifically explain the TCP client server programming model related code article is divided into 4 parts: 1. TCP Client Server programming model Flowchart 2. Network byte order and host byte order 3. Address structure for TCP programming 4. Detailed case code and explanation one: TCP Client Server programming model flowchart


The above two pictures will explain the whole process is clear, two: network byte order and host byte order byte order is the way to save data, divided into Big- endian storageAnd Small-End storage; where Network byte orderUsing the big-endian storage, and we used the Host byte orderThe default small-end storage so in our network programming process also need to the corresponding data (address port) byte-order conversion below is a few byte-order conversion function:


Each function has its specific meaning, such as the first function in the first diagram, htonl, and the ntop in the second picture.
character meaning
H Host (hosts)
To To
N Network
L Long
P Pointer
That's a good memory. Three: Address structure of TCP programming the first is a generic address structure

The second one is encapsulated.

These two data types can be converted to each other four: detailed case code and explanation below is the code for a case. Complete the following functions: The server receives a connection from the client, the server outputs the address of the client on the screen, and sends the current time to the client, and the client then outputs the time to the screen.

Service-Side code:

//tcp_server.c#include <netdb.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/socket.h>#include <time.h>#include <memory.h>#include <signal.h>voidPrintstructSockaddr_in *addr) {intPort2 = Ntohs (Addr->sin_port);Charip[ -];memset(IP,0,sizeof(IP)); Inet_ntop (af_inet, &AMP;ADDR-&GT;SIN_ADDR.S_ADDR, IP,sizeof(IP));printf("Server: (Client Address:%s (%d) connected) \ n", IP, port2);}voidDo_service (intCFD) {LongT = time (0);Char* s = ctime (&t); size_t size =strlen(s) *sizeof(Char);if(Write (CfD, S, size)! = size) perror ("Write error");}intFdvoidSig_handler (intSIG) {if(sig = = SIGINT) {Close (FD);Exit(1); }}intMainvoid){if(Signal (SIGINT, sig_handler) = = Sig_err) {Perror ("Signal SIGINT Error");Exit(1); }//First step to create socket    //af_inet:ipv4    //sock_stream:tcp    //0: Default protocol    if(FD = socket (af_inet, Sock_stream,0)) <0) Perror ("Socket create error");printf("Server:socket created\n");//These two lines resolve Bind error:address already in use    //Can make the bound IP be reused immediately after it is closed    intOn =1;intret = setsockopt (FD, Sol_socket, SO_REUSEADDR, &on,sizeof(on));///Second call bind bind socket to address port    structSockaddr_in sock_addr;memset(&AMP;SOCK_ADDR,0,sizeof(SOCK_ADDR)); sock_addr.sin_family = af_inet;intPort =12345; Sock_addr.sin_port = htons (port);//host byte order to network byte orderSOCK_ADDR.SIN_ADDR.S_ADDR = Inaddr_any;if(Bind (FD, (structsockaddr*) &sock_addr,sizeof(SOCK_ADDR)) <0) Perror ("Bind error");printf("Server:bind ok\n");//Third step call listen start monitoring (Specify port monitoring)    //Notify the system to accept connection requests from clients    //(Place the received client connection into a queue of length 10)    if(FD, listenTen) <0) Perror ("Listen error");printf("Server:listen ok\n");//Fourth step call the Accept function to get a client's request connection from the queue    //And returns a client socket file descriptor    //If there is no client connection request, it will block    ///The second parameter is used to obtain the address structure of the client    intCLIENT_FD;structSOCKADDR new_addr;intLen =sizeof(NEW_ADDR);if(client_fd = Accept (FD, &AMP;NEW_ADDR, &len) <0) Perror ("Accept Error");printf("Server:accept ok\n");//Answer (read client data, write data to client)Print (structsockaddr_in*) &new_addr); Do_service (CLIENT_FD);//Close socket fileClose (FD);printf("Server:close ok\n");return 0;}
To open the server after compiling:

It is clear that the server process is currently blocking state (accept), there are many ways to wait for the client to connect to the server, where my server process is in a bridged virtual machine such as we can open the browser in this machine with HTTP access to it:

The following is the information that the server process obtains:

Of course, to learn we have to complete the code for the client process in the TCP model:
//tcp_client.c#include <netdb.h>#include <unistd.h>#include <sys/socket.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <memory.h>Const intPort =12345;Const Char* IPAddr ="192.168.1.209";intMainvoid){intFdif(FD = socket (af_inet, Sock_stream,0)) <0) Perror ("Socket create error");printf("Client:socket created\n");structSockaddr_in serveraddr;memset(&AMP;SERVERADDR,0,sizeof(SERVERADDR)); serveraddr.sin_family = af_inet;//Host byte order change network byte order    //host to NetworkServeraddr.sin_port = htons (port);//pointer to NetworkInet_pton (Af_inet, ipaddr, &serveraddr.sin_addr.s_addr);//Call connect to specify the IP of the server    if(Connect (FD, (structsockaddr*) &serveraddr,sizeof(SERVERADDR)) <0) Perror ("Connect Error");printf("Client:connect ok\n");Charbuffer[1024x768];memset(Buffer,0,sizeof(buffer)); size_t size;if(size = read (fd, buffer,sizeof(buffer))) <0) Perror ("Read error");printf("Client Read content:%s", buffer); Close (FD);return 0;}
The display after the server process and the client process are connected:

Well, so far, our case is complete. Reprint Please specify source: Csdn_blog:axuank

Linux-socket TCP Client Server programming model and code explanation

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.