Client Server Example Program In C Language

Namaste Guys,



Today, In this post, I am going to share with you a very simple example of client and server model written in c language..
Actually, These scripts are very easy to understand but still, to make sure that all beginners will understand. I had used many comments in codes. These comments will help you to understand this script.

Note:

1. These Scripts are Tested In Ubuntu Only.
2. For More Description About Syntax, Use Ubuntu man page.


Client.c



  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// include header
#include <stdlib.h>       // standard library
#include <stdio.h>        // standard input output library
#include <sys/socket.h>   // socket
#include <sys/types.h>    // data info
#include <netinet/in.h>   // server object struct
#include <netdb.h>        // host struct


/*
 * 
 *      __author__: Suraj Singh Bisht
 *                  surajsinghbisht054@gmail.com
 *                  www.bitforestinfo.com 
 * 
 * ============================================================
 *                 Created During C socket practise
 * ============================================================
 * 
 *         Tested Only In Ubuntu
 *
 * */

// error handling function
void error(char *msg){
    perror(msg);
    exit(0);
}


// main function
int main(int argc, char *argv[]){
    // check argument for server_address, server_port
    if (argc<3){
        printf("Usages : %s server_ip_address Server_port\n", argv[0]);
        exit(0);
    }

    // decleare variables
    int sockd;                      // socket
    int portno;                     // portnumber
    int n;                          // to store data
    char buffer[256];               // to handle string characters
    struct sockaddr_in serv_addr;   // server address struct handling
    struct hostent *server;         // host struct 

    // port number 
    portno = atoi(argv[2]);

    // collect various information and return as hostent struct
    server = gethostbyname(argv[1]);

    // check server return struct
    if (server==NULL){
        error("Error: During Gethostbyname");
    }

// struct  hostent {
//        char    *h_name;        /* official name of host */
//        char    **h_aliases;    /* alias list */
//        int     h_addrtype;     /* host address type */
//        int     h_length;       /* length of address */
//        char    **h_addr_list;  /* list of addresses from name server */
// #define h_addr  h_addr_list[0]  /* address, for backward compatiblity */
// };
    
    // create socket
    sockd = socket(AF_INET, SOCK_STREAM, 0);

    if(sockd < 0){
        error("Error: During Socket Creation\n");
    }

    // time to clear server_addr struct
    bzero((char *)&serv_addr, sizeof(serv_addr));

    // time to insert values in serv_addr struct
    serv_addr.sin_family = AF_INET;    // Socket Family
    
    serv_addr.sin_port = htons(portno); // Port number

    // hmm, let's directly copy informations from server struct to serv_addr
    bcopy(
        (char *)server->h_addr,             // source
        (char *)&serv_addr.sin_addr.s_addr, // destination
        server->h_length                    // data length
        );

    // connect to server    
    n = connect(sockd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
    // check connection
    if (n<0){
        error("Error: During Establising Connection With Server.");
    }
    // print informations
    printf("[+] Connection Ready...\n");
    printf("[-] Enter Your Message : ");

    // read user input
    fgets(buffer, 255, stdin);

    // sent user input to socket
    n = write(sockd, buffer, strlen(buffer));
    if (n<0){
        error("Error: During message sending process");
    }
    // make sure, buffer is clean
    bzero(buffer, 256);

    // read 
    n = read(sockd,buffer, 255 );
    if (n<0){
        error("Error: During Reading Data");
    }
    printf("[+] Data Received : %s \n", buffer);


    return 0;
}
♥Dcode♥

Server.c



  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// include headers
#include <stdio.h>         // Standard Input Output Header
#include <stdlib.h>        // standard library
#include <sys/socket.h>   // Socket Header
#include <sys/types.h>    // Datatype For System Calls
#include <netinet/in.h>   // SOcket related data struct


/*
 * 
 *      __author__: Suraj Singh Bisht
 *                  surajsinghbisht054@gmail.com
 *                  www.bitforestinfo.com 
 * 
 * ============================================================
 *                 Created During C socket practise
 * ============================================================
 * 
 *         Tested Only In Ubuntu
 * 
 * */


// display error and exit
void error(char *msg){
    perror(msg);
    exit(0);
}

// main function
int main(int argc, char *argv[]){
    // check argument --
    if (argc<2){
        printf("Error; Please Provide Port Number As Argument.\n");
        printf("Usages : \n\t %s port_number \n", argv[0]);
        exit(0);
    }

    // initialise variables
    int sockd;  // To Handle Main Socket Function Object
    int newsock; // To handle Received Connection Socket From Client
    int port;    // Port number
    int clientlisten;  // client listening
    int n;       // to store number
    char buffer[256]; // to store client receiving messages


    // port number
    port = atoi(argv[1]); // Get Port Number As Integer


    /*
    
    struct sockaddr_in {
        short   sin_family;
        u_short sin_port;
        struct  in_addr sin_addr;
        char    sin_zero[8];
};
    
    */
    struct sockaddr_in client, server;

    // time to make sure, above struct buffer is clear... :) yup! little knowledge of exploitation    
    bzero((char *)&server, sizeof(server));

    // time to load, server struct (For Binding)

    server.sin_family = AF_INET;  // SOcket family
    server.sin_port = htons(port); // socket port
    server.sin_addr.s_addr = INADDR_ANY; // all clients allowed

    
    // socket initialise
    sockd = socket(AF_INET, SOCK_STREAM, 0);

    // check sockd 
    if (sockd <0){
        error("Something Wrong With Socket Creation Codes!");
    }

    // time to bind socket
    n = bind(sockd, (struct sockaddr *)&server, sizeof(server));

    // check bind
    if(n<0){
        error("Error: Something Wrong With Binding Codes.!");
    }
    // so, now our socket is ready to receive connections

    // 
    listen(sockd, 5); // limit client connections

    // wait and receive connection
    n = sizeof(client);
    newsock = accept(sockd, (struct sockaddr *)&client, &n);

    if (newsock<0){
        error("Error: During Receiving Connection From Clients.!");
    }

    n = read(newsock, buffer, 255); // Read Bytes From Socket And Save it in Buffer
    if(n<0){
        error("Error: During Reading Sent Data By Client.");
    } 
    printf("[+] Client Sent : %s\n", buffer);

    // so, we received message from client.. now it's time to reply back
    n = write(newsock, "HELLO Client", 13);

    if(n<0){
        error("Error: During Sending Data To Client");
    } 
    // return
    return 0;


}
♥Dcode♥

Compilation Command



1
2
3
:~# gcc client.c -o client

:~# gcc server.c -o server
♥Dcode♥



Share this

Related Posts

Previous
Next Post »