TCP Socket Programming

Source: Internet
Author: User
Tags bind socket sprintf strcmp strlen port number htons

For the socket does not understand can be viewed: C language through the socket programming TCP communication, Linux socket programming/socket detailed

First look at the program renderings

Tip If the server, directly through CTRL + Z shutdown, so that the program occupies the address is not released, the following actions are required

1.PS//view process

2.KILL-9 program PID//Forced Kill process

Service side:


Client:


Next is the code

Service side:

#include <sys/types.h> #include <sys/socket.h>//function library with sockets #include <netinet/in.h>//contains AF_INET related structures #include <arpa/inet.h>//operation functions with Af_inet #include <unistd.h> #include <stdlib.h> #include <stdio.h > #include <string.h>/* After listening, has been in the accept blocking state until there is a client connection, after input EOF, disconnect from the client, input quit shut down the server read EOF, disconnect and this client connection, read the Quit off
     
    Closed Server */#define PORT 3333 void Main () {printf ("program starts \ n");                  int s_fd,c_fd;                The server and the client socket identifier int S_len,c_len;    Server and client message length struct sockaddr_in s_addr;    Server socket address struct sockaddr_in c_addr;  
    Client socket int databytes=0;//Read message length//message char Sendbuf[bufsiz];  
    
    Char Recvbuf[bufsiz]; /*************************** Create socket **************************///socket function, failed return-1//int socket (int domain, int type  
    , int protocol); The first parameter represents the type of address used, typically IPv4 or af_inet//The second parameter represents the socket type: TCP is generally used SOCK_STREAM data stream//The third parameter is set to 0 s_fd = socket (af_inet,s Ock_stream,0);
        if (S_FD < 0) {perror ("Create socket failed");
    Return
    } printf ("Create socket succeeded \ n");
    /**************************** Open Address multiplexing *******************/int optval = 1;//1 Allow address reuse 0 prohibit int optlen = sizeof (optval);
    SetSockOpt (S_fd,sol_socket,so_reuseaddr,&optval,optlen); /******************** initializes the server socket *****************///htons and htonl the port and address to the network byte order//defines the domain in the address in the server, af_inet refers to IPv4 s_addr.
    sin_family = af_inet;
    Defines the socket port on the server S_addr.sin_port = htons (port);

    Define socket address//IP But the IP of this server, use macro Inaddr_any instead, represent 0.0.0.0, show all Address s_addr.sin_addr.s_addr = htonl (Inaddr_any);  
    /**************** binding socket Set port number and ip***********************///for functions such as bind,accept, the socket parameters are required to be cast to (struct sockaddr *) Bind three parameters: server-side socket file Descriptor S_len = sizeof (S_ADDR);//Set Send message length if (Bind (S_FD, (struct sockaddr*) &s_addr,s_len) &L T
        0) {perror ("bind socket failed");
    Return
    } printf ("Bind socket succeeded \ n"); /***************** set the socket on the server as the listening state *******************/
    Monitoring, maximum number of connections (Listen (s_fd,10) < 0) {perror ("failed to listen");
    Return

    } printf ("Monitor successful port:%d\n", port);
        while (1) {printf ("Wait for connection ... \ n");
        Fflush (stdin) refreshes the standard input buffer, fflush (STDOUT) refreshes the standard output buffer fflush (stdout);
        Set Receive message length C_len = sizeof (C_ADDR); /******************** receives a client connection request *************************///calls the Accept function, it goes into a blocking state//accept returns a socket file descriptor so that the The server side has two sockets of the file descriptor,//S_FD and C_FD//S_FD still continue in the listening state, C_FD is responsible for receiving and sending data//c_addr is an outgoing parameter, when accept returns, the outgoing client's  
        The address and port number//c_len is an incoming-outgoing parameter, passing in the length of the c_addr of the buffer supplied by the caller to avoid a buffer overflow.  
        Outgoing is the actual length of the client address structure body.
        Error return-1 C_FD = Accept (s_fd, (struct sockaddr*) &c_addr, (socklen_t*) &c_len);
            if (C_FD < 0) {perror ("Accept failed");
        Continue
        } printf ("New connection: \ n"); 
        Inet_ntoa IP Address translation function, converts network byte-order IP to dotted decimal IP//Expression: char *inet_ntoa (struct in_addr); PrintF ("\tip is%s\n", Inet_ntoa (C_ADDR.SIN_ADDR));  
        printf ("\tport is%d\n", htons (C_addr.sin_port));
        printf ("Wait for message ... \ n");
            while (1) {databytes=0; 
            /************************* Receive data ***********************/printf ("--------------------read:");
            Fflush (stdout);
            Databytes = recv (c_fd,recvbuf,bufsiz,0);
                if (Databytes < 0) {perror ("read failed");
            Continue
            }else if (databytes = = 0) {printf ("no message \ n");

            }else printf ("%s\n", recvbuf);
                Determine exit, quit, disconnect, close client if (strncmp (Recvbuf, "Quit", 4) = = 0) {sprintf (Recvbuf, "%s", "EOF");
                Send (C_fd,recvbuf,sizeof (RECVBUF) +1,0);
                Close the connection close (S_FD);
                printf ("Shut down server \ n"); 
                printf ("program end \ n");
            Return }//eof, disconnect if (strncmp (Recvbuf, "EOF ", 3) = = 0) {break; }/************************ sends data *************************/printf ("-------------     
            -------send: ");
            scanf ("%s", sendbuf);
            
            Send (C_fd,sendbuf,strlen (SENDBUF) +1,0);
                Determine exit, quit, disconnect, close client if (strncmp (SendBuf, "Quit", 4) = = 0) {sprintf (SendBuf, "%s", "EOF");
                Send (C_fd,sendbuf,sizeof (SENDBUF) +1,0);
                Close the connection close (S_FD); 
                printf ("program end \ n");
            Return
            }//eof, disconnect if (strncmp (SendBuf, "EOF", 3) = = 0) {break;
    }}//while send and receive messages printf ("Disconnected \ n \ nthe");
    }//while Accept//close connection close (S_FD); 
    printf ("program end \ n");
Return
 }

Client:

#include <sys/types.h> #include <sys/socket.h>//function library with sockets #include <netinet/in.h>//contains AF_INET related structures #include <arpa/inet.h>//operation functions with Af_inet #include <unistd.h> #include <stdlib.h> #include <stdio.h   
> #include <string.h>/* After connecting to the server, it will not stop looping, wait for input, enter EOF, disconnect, enter quit, disconnect and shut down the server after reading EOF, disconnect, read quit, disconnect and shut down the server */

    #define PORT 3333 void Main () {printf ("program starts \ n"); 
    A client socket identifier that requires only a socket file descriptor for communicating with the client int sockfd;
    Describes the client socket struct SOCKADDR_IN addr;
    Message length int databytes = 0;  
    Message Char Sendbuf[bufsiz];  
    
    Char Recvbuf[bufsiz];
    Create Socket SOCKFD = socket (af_inet,sock_stream,0);
        if (SOCKFD < 0) {perror ("Create socket failed");
    Return
    } printf ("Create socket succeeded \ n"); /******************** initializes the client socket *****************///htons and htonl the port and address to the network byte order//defines the domain in the address in the client, af_inet refers to IPv4 addr.si
    n_family = af_inet;
    Defines the socket port on the server Addr.sin_port = htons (port); Specify server-side IP, local test: 127.0.0.1//inet_addr () function, convert dotted decimal IP to network byte order IP addr.sin_addr.s_addr = inet_addr ("127.0.0.1"); /********************** Connection Server **********************/if (Connect (SOCKFD, (struct sockaddr *) &addr, sizeof (addr)) & Lt  
        0) {perror ("Connection Server failed");  
    Return
    } printf ("Connect to server ... \ n");
        while (1) {/******************* sends the message ************************/printf ("--------------------send:");   
        scanf ("%s", sendbuf);

        Send (Sockfd,sendbuf,strlen (SENDBUF) +1,0);
        if (strcmp (SendBuf, "quit") = = 0) {//Shutdown server//shutdown client break;
        } if (strcmp (SendBuf, "EOF") = = 0) {//close client break;
        }//Read the message printf ("--------------------read:");
        Fflush (stdout);  
        Databytes = recv (SOCKFD, RECVBUF, 200, 0);
        printf ("%s\n", recvbuf); if (strncmp (Recvbuf, "Quit", 4) = = 0) {//Shut down the server//Shut down the client BreaK
        } if (strncmp (Recvbuf, "EOF", 3) = = 0) {//close client break;
    }}//Closes the connection close (SOCKFD); 
    printf ("program end \ n");
Return
 }

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.