You are on page 1of 2

Server

#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#define PORT 8080

int main(){

int opt = 1;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[20] = {}, username[] = "ajay", password[] = "123";
char uname[10], pword[10];
printf("Creating socket\n");
int socket_ds = socket(AF_INET, SOCK_STREAM, 0);

if(socket_ds < 0) {
printf("\nError creating socket");
exit(1);
}

address.sin_family = AF_INET;
address.sin_port = htons(PORT);
address.sin_addr.s_addr = INADDR_ANY;

printf("Binding socket\n");
if(bind(socket_ds, (struct sockaddr*)&address, sizeof(address)) < 0){
printf("\nBind failed");
exit(1);
}

printf("Listening...\n");
if(listen(socket_ds, 3) < 0){
printf("\nListen failed");
exit(1);
}

int new_sock = accept(socket_ds, (struct sockaddr*)&address, (socklen_t


*)&addrlen);
if(new_sock < 0){
printf("\nAccept failed");
exit(1);
}
printf("Connection accepted\n");
read(new_sock, uname, 5);
read(new_sock, pword, 3);

if(strcmp(uname, username) != 0 || strcmp(pword, password) != 0){


printf("Authentication failed\n");
close(new_sock);
shutdown(socket_ds, SHUT_RDWR);
exit(1);
}
printf("User Authenticated\n");
int val_read = read(new_sock, buffer, 15);

printf("Input string : %s\n", buffer);

int i;
int len = strlen(buffer);
for(i = 0 ; i < len/2; ++i){
char temp = buffer[i];
buffer[i] = buffer[len - i - 1];
buffer[len - i - 1] = temp;
}
send(new_sock, buffer, strlen(buffer), 0);
close(new_sock);
shutdown(socket_ds, SHUT_RDWR);
return 0;
}
Client

#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#define PORT 8080
int main(){

int opt = 1;
char hello[20] = "good morning\0";

char username[10], password[10];


struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024];
int socket_ds = socket(AF_INET, SOCK_STREAM, 0);

printf("Creating socket\n");
if(socket_ds < 0) {
printf("\nError creating socket");
exit(1);
}

address.sin_family = AF_INET;
address.sin_port = htons(PORT);

if (inet_pton(AF_INET, "127.0.0.1", &address.sin_addr)


<= 0) {
printf("\nInvalid address");
exit(1);
}

printf("Connecting to server\n");
if(connect(socket_ds, (struct sockaddr*)&address, sizeof(address)) < 0){
printf("\nConnection failed");
exit(1);
}

printf("\nInput username : ");


scanf("%s", username);
username[strlen(username)] = '\0';

send(socket_ds, username, strlen(username), 0);

printf("\nInput password : ");


scanf("%s", password);
password[strlen(password)] = '\0';
send(socket_ds, password, strlen(password), 0);
send(socket_ds, hello, strlen(hello), 0);

char resp[100] = {};


read(socket_ds, resp, strlen(hello));
printf("Response from server : %s\n", resp);

shutdown(socket_ds, SHUT_RDWR);
close(socket_ds);
return 0;
}

You might also like