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.
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
your program isot easy easy to understand also not executable . plz make some changes in program
its working bro 🙂
how to run this code in ubuntu
please send me the procedure
commands for ubuntu:
For compiling a code:
gcc program_name.c -o any_name.out (hit enter)
for running:
./any_name.out
@Abrar Ahmad
Thanks.. worked
vi filename.c
compile : cc -o filename filename.c
run: ./filename
go to terminal and type this
gcc your program name
Then compiled and output type
./a.out
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
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
It works thanks
hey can u help me with this ??
alert(“test”);
lame wannabe hacker. leaces traces.. hehe
thank you very much its not working
very helpful for me to understand the client-server communication.
how to run this code ?
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
First run server binary, then client binary.
How to resolve Permission denied errors during execution of ./server.c and ./client.c?
addsudo in front of cc or gcc
add sudo in front of cc or gcc
./server
not ./server.c
How can I make it such that there are several server queuing to listen on the server.Thanks
command all the terminals and run
This was incredibly easy to understand and execute, thanks for the great example!
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.
Yeah , Good stuff , its easy to understand and anyone can execute it who know ‘C’.
This is great but I wish you had some better syntax highlighting, it’s hard to tell the comments from the code.
thankyou so much bro it’s work 😀
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
how can i modify this codes such that the client sends an arithmetic operation for the server to perfom ?
it is not executable….error at run time in server code
change ur ip address and port number
i want to run client server program in my boss linux how can i get my ip address to run these
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
How to communicate back to client from server?
Thanks you very much man !!! That really helped me to understand and fix my program !!!
gcc -o
gcc -o
open two terminals
First run the server binary using ./ in one terminal
then in another terminal ./
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
that header file missed that is #include
arpa/inet.h
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.
user input message has to pass to one to other please help me with this
thanks in advance
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();
}
}
How to run server on my ubuntu desktop and client on my beaglebone black? They are connected through ethernet. Kindly help.
the #inlude , create me an error
ur code need to add #include to compile
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?
can u explain this line of code
mainly the 2nd parameter.
how to change ip address and port number
use —-
gcc
Can i please get d algoritm of te above code?
Please tell me why the this program error in header file:#include ?????
in visual studio 2010 its not executing…. give me suggestions
This is for linux sockets , windows has its own sockets.
http://www.binarytides.com/winsock-socket-programming-tutorial/
struct sockaddr_in has no member named in sin famaly why this error arise and how to solve it
in client code
storage size of serverAddr ist’t know is error faceing
also say reason and how to solve it
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…
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
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.
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.
I want code of multiple servers with one client, is it possible to make ? Can anyone send me the code for that please sir..