Example of Client-Server Program in C (Using Sockets and TCP)


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

Below you’ll find an example of a very simple client-server program in C. Basically the client connects to the server, the server sends the message “Hello World”, and the client prints the received message.

client-server-tcp-c

Keep in mind that I am configuring the settings manually. If you want your code to be IPV4-IPV6 agnostic, IP agnostic and portable to different plataforms you can use the getaddrinfo() function, as explained in this tutorial.

Second, I am not doing error checking on most function calls. You should implement those checks if you are going to use the code for a real project.

Third, if you want more details about the functions or their arguments please check the man page of each one.

Finally, to test the code you just need to run the server on a terminal and then run the client on a different terminal (or run the server as a background process and then run the client on the same terminal).

Server Code

/****************** SERVER CODE ****************/

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>

int main(){
  int welcomeSocket, newSocket;
  char buffer[1024];
  struct sockaddr_in serverAddr;
  struct sockaddr_storage serverStorage;
  socklen_t addr_size;

  /*---- Create the socket. The three arguments are: ----*/
  /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
  welcomeSocket = socket(PF_INET, SOCK_STREAM, 0);
  
  /*---- Configure settings of the server address struct ----*/
  /* Address family = Internet */
  serverAddr.sin_family = AF_INET;
  /* Set port number, using htons function to use proper byte order */
  serverAddr.sin_port = htons(7891);
  /* Set IP address to localhost */
  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  /* Set all bits of the padding field to 0 */
  memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

  /*---- Bind the address struct to the socket ----*/
  bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));

  /*---- Listen on the socket, with 5 max connection requests queued ----*/
  if(listen(welcomeSocket,5)==0)
    printf("Listening\n");
  else
    printf("Error\n");

  /*---- Accept call creates a new socket for the incoming connection ----*/
  addr_size = sizeof serverStorage;
  newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size);

  /*---- Send message to the socket of the incoming connection ----*/
  strcpy(buffer,"Hello World\n");
  send(newSocket,buffer,13,0);

  return 0;
}

Client Code

/****************** CLIENT CODE ****************/

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>

int main(){
  int clientSocket;
  char buffer[1024];
  struct sockaddr_in serverAddr;
  socklen_t addr_size;

  /*---- Create the socket. The three arguments are: ----*/
  /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
  clientSocket = socket(PF_INET, SOCK_STREAM, 0);
  
  /*---- Configure settings of the server address struct ----*/
  /* Address family = Internet */
  serverAddr.sin_family = AF_INET;
  /* Set port number, using htons function to use proper byte order */
  serverAddr.sin_port = htons(7891);
  /* Set IP address to localhost */
  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  /* Set all bits of the padding field to 0 */
  memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

  /*---- Connect the socket to the server using the address struct ----*/
  addr_size = sizeof serverAddr;
  connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size);

  /*---- Read the message from the server into the buffer ----*/
  recv(clientSocket, buffer, 1024, 0);

  /*---- Print the received message ----*/
  printf("Data received: %s",buffer);   

  return 0;
}

You might also like: Sockets Programming in C Using UDP Datagrams

62 thoughts on “Example of Client-Server Program in C (Using Sockets and TCP)

        1. Abrar Ahmad

          commands for ubuntu:
          For compiling a code:
          gcc program_name.c -o any_name.out (hit enter)
          for running:
          ./any_name.out

          Reply
        2. Shital

          On ubuntu terminal
          compile server program as
          gcc server.c -o server
          compile client program as
          gcc client.c -o client

          and run:
          on one terminal
          ./server
          Listening
          on another terminal
          ./client
          Data received: Hello World

          Reply
      1. aditya darekar

        I am getting this error
        *
        tcpserver.c:25:32: warning: implicit declaration of function ‘inet_addr’ [-Wimplicit-function-declaration]
        serverAddr.sin_addr.s_addr = inet_addr(“localhost”);
        *
        #help

        Reply
      1. Bijay

        compile client.c using cc -o client client.c
        and also compile server using cc -o server server.c

        then open two terminal of the current working directory then simultaneously in client and server
        run the executables like

        ./client.c
        ./server.c

        You will get the output.

        Cheers
        Bijay

        Reply
  1. Dulthumun Vijay

    How do I write a program in c based on tcp server/client? The client should update the server with its latest IPv6 address every time it changes its address.

    Reply
  2. Chester T Field

    This is great but I wish you had some better syntax highlighting, it’s hard to tell the comments from the code.

    Reply
    1. la

      hey plz tell how to get output fa this above server and client program
      what are all the arguments v need to pass nd where it should be pass

      Reply
  3. Dankam Therese

    how can i modify this codes such that the client sends an arithmetic operation for the server to perfom ?

    Reply
  4. Fevex yumnam

    use gcc compiler to run this code
    e.g. gcc server.c -o any_name

    gcc server.c && ./any_name port_number

    portnumber can be 8080 or 8888

    leave it running

    open another terminal

    gcc client.c -o any_name1

    ./any_name localhost 8080

    hope you know it now

    Reply
  5. Vijay

    gcc -o
    gcc -o
    open two terminals
    First run the server binary using ./ in one terminal
    then in another terminal ./

    Reply
  6. Badike Sekhar

    I think you missed the header file for inet_addr(“IP address”); in your client and server program so it is showing below warning::
    warning: implicit declaration of function ‘inet_addr’ [-Wimplicit-function-declaration]

    If you want to overcome that warning you have to add the header file::#include
    for both client and server,other than that it is very good client and server c program and very use full to understand the Using Sockets and TCP.

    thanking you

    Reply
  7. Ryan

    When I run the app in the IDE it runs perfectly, but after I built it and ran it in the terminal I get a segmentation fault.

    I ran it through gdb and got:
    Program received signal SIGSEGV, Segmentation fault.
    _IO_fgets (buf=0x6032b0 “”, n=6, fp=0x0) at iofgets.c:47
    47 iofgets.c: No such file or directory.
    (gdb) bt
    #0 _IO_fgets (buf=0x6032b0 “”, n=6, fp=0x0) at iofgets.c:47
    #1 0x00000000004013fa in get_conf () at cServer.c:119
    #2 0x0000000000401606 in main () at cServer.c:191

    I am not so good at understanding the debug output.

    Any help?

    Cheers,
    Ryan.

    Reply
  8. Paul

    Thanks , I modified the server to listen on multiple ports and to multiple clients.

    ———— Server ——————-
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.spi.AbstractSelectableChannel;
    import java.util.Iterator;
    import java.util.Set;

    public class SelectorExample {
    public static void main(String[] args) throws IOException, InterruptedException {

    // Get selector
    Selector selector = Selector.open();
    System.out.println(“Selector open: ” + selector.isOpen());

    // Get server socket channel and register with selector
    ServerSocketChannel server = ServerSocketChannel.open();
    InetSocketAddress hostAddress = new InetSocketAddress(“localhost”, 5454);
    server.socket().bind(hostAddress);
    server.configureBlocking(false);
    server.register(selector, SelectionKey.OP_ACCEPT, “Server1”);

    ServerSocketChannel server2 = ServerSocketChannel.open();
    InetSocketAddress hostAddress2 = new InetSocketAddress(“localhost”, 5455);
    server2.socket().bind(hostAddress2);
    server2.configureBlocking(false);
    server2.register(selector, SelectionKey.OP_ACCEPT, “Server2”);

    ServerSocketChannel server3 = ServerSocketChannel.open();
    InetSocketAddress hostAddress3 = new InetSocketAddress(“localhost”, 5456);
    server3.socket().bind(hostAddress3);
    server3.configureBlocking(false);
    server3.register(selector, SelectionKey.OP_ACCEPT, “Server3”);

    for (;;) {
    System.out.println(“Waiting for select…”);
    int noOfKeys = selector.select();
    System.out.println(“Number of selected keys: ” + noOfKeys);
    Set selectedKeys = selector.selectedKeys();

    Iterator iter = selectedKeys.iterator();

    while (iter.hasNext()) {
    SelectionKey ky = iter.next();

    if (ky.isAcceptable()) {
    // Accept the new client connection
    String serv = (String) ky.attachment();

    @SuppressWarnings(“resource”)
    SocketChannel client = null;
    if (serv.equals(“Server1”)) {
    client = server.accept();
    } else if (serv.equals(“Server2”)) {
    client = server2.accept();
    } else if (serv.equals(“Server3”)) {
    client = server3.accept();
    }

    if (client != null) {
    client.configureBlocking(false);
    // Add the new connection to the selector
    client.register(selector, SelectionKey.OP_READ);
    System.out.println(“Accepted new connection from client: ” + client);
    }

    } else if (ky.isReadable()) {
    // Read the data from client
    SocketChannel client = (SocketChannel) ky.channel();

    ByteBuffer buffer = ByteBuffer.allocate(256);
    client.read(buffer);
    String output = new String(buffer.array()).trim();
    System.out.println(“Message read from client :” + output);
    buffer.flip();
    client.write(buffer);
    buffer.clear();

    if (output.equals(“Bye.”)) {
    client.close();
    System.out.println(“Client messages are complete; close.”);
    }

    } // end if (ky…)

    iter.remove();

    } // end while loop

    } // end for loop

    }

    }
    —————- Client ———————

    import java.nio.channels.SocketChannel;
    import java.nio.ByteBuffer;
    import java.io.IOException;
    import java.net.InetSocketAddress;

    public class SocketClientExample {
    public static void main (String [] args)
    throws IOException, InterruptedException {
    int port = Integer.parseInt(args[0]);

    InetSocketAddress hostAddress = new InetSocketAddress(“localhost”, port);
    SocketChannel client = SocketChannel.open(hostAddress);

    System.out.println(“Client sending messages to server…”);

    // Send messages to server
    String [] messages = new String [] {“Time goes fast.”, “What now?”, “Bye.”};
    for (int i = 0; i < messages.length; i++) {
    byte [] message = new String(messages [i]).getBytes();
    ByteBuffer buffer = ByteBuffer.wrap(message);
    client.write(buffer);
    buffer.clear();
    client.read(buffer);
    String response = new String( buffer.array()).trim();
    System.out.println("Response :"+response);
    buffer.clear();
    Thread.sleep(3000);
    }
    client.close();

    }
    }

    Reply
  9. Umer Zia

    How to run server on my ubuntu desktop and client on my beaglebone black? They are connected through ethernet. Kindly help.

    Reply
  10. jenny

    Hi, Iam new to networking concepts, how can i run this code? like can i make one of my pc a server and the other pc as a client in eclipse ide? and I think in the both systems i need to have linux right?

    Reply
  11. Batman

    I’ve never seen so many stupid people in the same place, this tutorial assumes, 1) you know the difference between an executable and its source code, 2) you know what the living fck a compiler is…

    Reply
  12. HSingh

    Hi Everyone,

    I am working on an embedded systems project using Beaglebbone Black
    Using the server / client programs in this forum i am trying to pass string from client to server
    the beaglebone is the server and logged on using Remote login through SSh and the pc has fedora and a normal terminal is being used to connect to the server
    How to connect the 2 systems running on different platforms

    caan anyone please help

    Reply
  13. some1

    Why there’s no loops on the server code? How is that possible? I understand each individual function call, but I don’t get the overall picture.

    Reply
    1. some1

      Oh, I got it. The code is bugging on my machine for some reason. I’m getting random characters on the client side, and the server keeps running. That’s why I was expecting some kind of loop on the server side, but sometimes the client prints “Hello world” as it should and the server program terminates.

      Reply
  14. PAVAN KUMAR

    I want code of multiple servers with one client, is it possible to make ? Can anyone send me the code for that please sir..

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *