Reverse a string in C/C++ using Client Server model

Here we will see how we can create a system, where we will create one client, and a server, and the client can send one string to the server, and the server will reverse the string, and return back to the client.

Here we will use the concept of socket programming. To make the client server connection, we have to create port. The port number is one arbitrary number that can be used by the socket. We have to use the same port for client and the server to establish the connection.

To start the program, start the server program first −

gcc Server.c –o server

Then start client program −

gcc Client.c –o server

Now the server will wait for a string from client. We have to take a string as input from the client side, then it will be transferred. The server will print the string, and also send the reversed string. After that client will print the reversed string from server.

Example

//Client Side Code
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define PORT 4000
main() {
   struct sockaddr_in address;
   int my_socket = 0, valread;
   struct sockaddr_in server_address;
   char str[100];
   int l;
   printf("Enter a String:");
   fgets(str, 100, stdin); //read string until new line character is pressed
   char buffer[1024] = { 0 }; //create a buffer and fill with 0
   // Creating socket file descriptor
   if ((my_socket = socket(AF_INET, SOCK_STREAM, 0)) 

Example

//Server Side Code
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define PORT 4000
char *strrev(char *str){
   char *p1, *p2;
   if (! str || ! *str)
      return str;
   for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2){
      *p1 ^= *p2;
      *p2 ^= *p1;
      *p1 ^= *p2;
   }
   return str;
}
main() {
   int server_fd, new_socket, valread;
   struct sockaddr_in address;
   char str[100];
   int addrlen = sizeof(address);
   char buffer[1024] = { 0 };
   int i, j, temp;
   int l;
   char* message = "Welcome to the server"; //initial message
   // Creating socket file descriptor
   if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
      perror("Socket connection failed");
      exit(EXIT_FAILURE);
   }
   address.sin_family = AF_INET;
   address.sin_addr.s_addr = INADDR_ANY;
   address.sin_port = htons(PORT);
   if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) 

Output

Updated on: 2019-07-30T22:30:26+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements