How to Send from Server command propts and take output from client - c

server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]){
int portno;
int sockfd, ret;
struct sockaddr_in serverAddr;
int newSocket;
struct sockaddr_in newAddr;
socklen_t addr_size;
char buffer[1024];
pid_t childpid;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0){
printf("[-]Error in connection.\n");
exit(1);
}
printf("[+]Server Socket is created.\n");
portno = atoi(argv[1]);
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(portno);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(ret < 0){
printf("[-]Error in binding.\n");
exit(1);
}
printf("[+]Bind to port %d\n", portno);
if(listen(sockfd, 10) == 0){
printf("[+]Listening....\n");
}else{
printf("[-]Error in binding.\n");
}
while(1){
newSocket = accept(sockfd, (struct sockaddr*)&newAddr, &addr_size);
if(newSocket < 0){
exit(1);
}
printf("[+]Bind to port %d\n", portno);
if(listen(sockfd, 10) == 0){
printf("[+]Listening....\n");
}else{
printf("[-]Error in binding.\n");
}
while(1){
newSocket = accept(sockfd, (struct sockaddr*)&newAddr, &addr_size);
if(newSocket < 0){
exit(1);
}
printf("Connection accepted from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
if((childpid = fork()) == 0){
close(sockfd);
while(1){
recv(newSocket, buffer, 1024, 0);
if(strcmp(buffer, "END") == 0){
printf("Disconnected from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
break;
}else{
printf("Client: %s\n", buffer);
send(newSocket, buffer, strlen(buffer), 0);
bzero(buffer, sizeof(buffer));
}
}
}
}
close(newSocket);
return 0;
}
}
Client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]){
int portno;
int clientSocket, ret;
struct sockaddr_in serverAddr;
char buffer[1024];
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if(clientSocket < 0){
printf("[-]Error in connection.\n");
exit(1);
}
printf("[+]Client Socket is created.\n");
portno = atoi(argv[2]);
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(portno);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(ret < 0){
printf("[-]Error in connection.\n");
exit(1);
}
printf("[+]Connected to Server.\n");
while(1){
printf("Client: \t");
scanf("%s", &buffer[0]);
send(clientSocket, buffer, strlen(buffer), 0);
if(strcmp(buffer, "END") == 0){
close(clientSocket);
printf("[-]Disconnected from server.\n");
exit(1);
}
if(recv(clientSocket, buffer, 1024, 0) < 0){
printf("[-]Error in receiving data.\n");
}else{
printf("Server: \t%s\n", buffer);
}
}
return 0;
}
And i want each time i run server and client, when i run command ls from server take the output from client and other commands too like ls-l and ls -l | wc and ls > result.txt
I try running many examples i found but nothing just running command from server and take the same output to my client

Related

Communication between containers on Docker

I have 3 services in C and I want they communicate toghether with a docker compose but I can't.
I tried with a two simples images and they connected but not in a docker compose.
The problem are the function connect(). He return -1 beaucause in the inet_addr(), I want to include the image who the message will be sent.
I use 3 images with gcc for to compile C files.
# FILE : service1.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
//#define PORT_SERV 4443
#define PORT_CLI 4443
time_t t;
static void * client(){
int clientSocket, ret;
struct sockaddr_in serverAddr;
char buffer[256];
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket < 0) {
printf("[Client -] Error in Client Socket \n");
fflush(stdout);
exit(1);
}
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT_CLI);
serverAddr.sin_addr.s_addr = inet_addr("image1");
ret = connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
while (ret < 0) {
printf("[Client -] Erreur de connexion. Nouvel essai ! %d\n", ret);
fflush(stdout);
sleep(3);
ret = connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
}
printf("[Client +] Connected to Server.\n");
fflush(stdout);
while(1){
time(&t);
strcpy(buffer, "Bonjour depuis le service 1");
sleep(5);
send(clientSocket, buffer, strlen(buffer), 0);
if (strcmp(buffer, ": exit") == 0) {
printf("[Client -] Disconnected from server.\n");
fflush(stdout);
exit(1);
}
if (recv(clientSocket, buffer, 256, 0) < 0) {
printf("[Client -] Error in receiving data. \n");
fflush(stdout);
} else {
printf("%sService 1 : %s \n", ctime(&t), buffer);
fflush(stdout);
}
}
}
int main(void){
//pthread_t s,
pthread_t c;
int ret = 0;
ret = pthread_create(&c, NULL, &client, NULL);
/*ret = pthread_create(&s, NULL, &server, NULL);
if (! ret) {
ret = pthread_create(&c, NULL, &client, NULL);
}*/
//pthread_join(s, NULL);
pthread_join(c, NULL);
return 0;
}
FILE = service2.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define PORT_SERV 4442
#define PORT_CLI 4443
time_t t;
time_t t2;
static void * server(){
int sockfd, ret;
struct sockaddr_in serverAddr;
int newSocket;
struct sockaddr_in newAddr;
char buffer[256];
pid_t childpid;
socklen_t addr_size;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("[-] Error in Client Socket\n");
fflush(stdout);
exit(1);
}
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT_SERV);
serverAddr.sin_addr.s_addr = inet_addr("image1");
ret = bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if (ret < 0) {
printf("[-] Error in binding\n");
fflush(stdout);
exit(1);
}
printf("[+] Bind to port %d\n", PORT_CLI);
fflush(stdout);
if (listen(sockfd, 10) == 0) {
printf("[+] Listening...\n");
fflush(stdout);
} else {
printf("[-] Error in binding\n");
fflush(stdout);
}
while(1)
{
newSocket = accept(sockfd, (struct sockaddr*)&newAddr, &addr_size);
if(newSocket < 0) {
exit(1);
}
printf("Connection accepted from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
fflush(stdout);
if ((childpid = fork()) == 0)
{
close(sockfd);
while (1)
{
time(&t2);
recv(newSocket, buffer, 256, 0);
if(strcmp(buffer, ": exit") == 0){
printf("Disconnected from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
fflush(stdout);
break;
} else {
printf("%sClient : %s\n", ctime(&t2), buffer);
fflush(stdout);
send(newSocket, buffer, strlen(buffer), 0);
bzero(buffer, sizeof(buffer));
}
}
}
}
close(newSocket);
}
static void * client(){
int clientSocket, ret;
struct sockaddr_in serverAddr;
char buffer[256];
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket < 0) {
printf("[-] Error in connection\n");
fflush(stdout);
exit(1);
}
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT_CLI);
serverAddr.sin_addr.s_addr = inet_addr("image3");
ret = connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
while (ret < 0) {
printf("[-] Erreur de connexion. Nouvelle tentative !\n");
fflush(stdout);
sleep(3);
ret = connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
}
printf("[+] Connected to Server.\n");
while(1){
time(&t);
strcpy(buffer, "Bonjour depuis le service 2");
sleep(5);
send(clientSocket, buffer, strlen(buffer), 0);
if (strcmp(buffer, ": exit") == 0) {
printf("[Client -] Disconnected from server.\n");
fflush(stdout);
exit(1);
}
if (recv(clientSocket, buffer, 256, 0) < 0) {
printf("[Client -] Error in receiving data. \n");
fflush(stdout);
} else {
printf("%sService 2: %s \n", ctime(&t), buffer);
fflush(stdout);
}
}
}
int main(void){
pthread_t s, c;
int ret = 0;
ret = pthread_create(&s, NULL, &server, NULL);
if (! ret) {
ret = pthread_create(&c, NULL, &client, NULL);
}
pthread_join(s, NULL);
pthread_join(c, NULL);
return 0;
}
FILE = service3.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define PORT_SERV 4444
//#define PORT_CLI 4443
time_t t;
time_t t2;
static void * server(){
printf("Hello World!\n");
int sockfd, ret;
struct sockaddr_in serverAddr;
int newSocket;
struct sockaddr_in newAddr;
char buffer[256];
pid_t childpid;
socklen_t addr_size;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("[-] Error in connection\n");
exit(1);
}
printf("[+] Client Socket is created !\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT_SERV);
serverAddr.sin_addr.s_addr = inet_addr("image2");
ret = bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if (ret < 0) {
printf("[-] Error in binding\n");
exit(1);
}
printf("[+] Bind to port %d\n", 4444);
if (listen(sockfd, 10) == 0) {
printf("[+] Listening...\n");
} else {
printf("[-] Error in binding\n");
}
while(1)
{
newSocket = accept(sockfd, (struct sockaddr*)&newAddr, &addr_size);
if(newSocket < 0) {
exit(1);
}
printf("Connection accepted from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
fflush(stdout);
if ((childpid = fork()) == 0)
{
close(sockfd);
while (1)
{
time(&t2);
recv(newSocket, buffer, 256, 0);
if(strcmp(buffer, ": exit") == 0){
printf("Disconnected from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
break;
} else {
printf("%sClient : %s\n", ctime(&t2), buffer);
send(newSocket, buffer, strlen(buffer), 0);
bzero(buffer, sizeof(buffer));
}
}
}
}
close(newSocket);
}
int main(void){
printf("Hello World!\n");
fflush(stdout);
pthread_t s;
//pthread_t c;
int ret = 0;
printf("Thread du server\n");
ret = pthread_create(&s, NULL, &server, NULL);
/*if (! ret) {
printf("Thread du client\n");
ret = pthread_create(&c, NULL, &client, NULL);
}*/
pthread_join(s, NULL);
//pthread_join(c, NULL);
return 0;
}
File = docker-compose.yml
version: "3.8"
services:
image1:
build: ./image1
image: service1:1.0
networks:
- mynet
ports:
- 127.0.0.1:4441:4441
image2:
build: ./image2
image: service2:1.0
networks:
- mynet
ports:
- 127.0.0.1:4442:4442
image3:
build: ./image3
image: service3:1.0
networks:
- mynet
ports:
- 127.0.0.1:4443:4443
networks:
mynet:
I build and run with docker compose build docker compose up -d and the images don't connect toghether.
Thanks !

Multiclient and server commandline argument issues

I have code for a server that can handle multiple clients. The client program can connect to the server and issue Unix commands such as ls, date, clear, etc. I have two problems that I cannot figure out. 1) When I initially type ls as an argument it will return some weird garbage, and then if I do ls again then it starts working properly. So only in the beginning, it will give me garbage. 2) When I type the argument 'ps -ael' into the terminal, it will work properly, but then after that I get a 'Failed' message, which is coming from the Client code, specifically at the while(1) loop where if (send(clientSocket, s, echolen, 0) != echolen), this is where the error is occurring. I was curious to know if someone could point to what the problem could be, I think it might be because I create a char array that's too big but I'm not sure.
Client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 4444
#define BUFFSIZE 2048
int main(int argc, char *argv[]){
int clientSocket, ret, portnum;
struct sockaddr_in serverAddr;
int received = 0;
unsigned int echolen;
char buffer[1024];
if(argc < 3){
fprintf(stderr,"usage %s <server-ip-addr> <server-port>\n", argv[0]);
exit(0);
}
portnum = atoi(argv[2]);
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if(clientSocket < 0){
printf("Error in connection.\n");
exit(1);
}
printf("Client Socket is created.\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
// memset(&buffer, '\0', sizeof(buffer));
// serverAddr.sin_family = AF_INET;
// serverAddr.sin_port = htons(PORT);
// serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
// bzero((char *) &serverAddr, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
if(!inet_aton(argv[1], &serverAddr.sin_addr)){
fprintf(stderr, "Error invalid server IP address\n");
exit(1);
}
serverAddr.sin_port = htons(portnum);
ret = connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(ret < 0){
printf("Error in connection.\n");
exit(1);
}
printf("Connected to server.\n");
char s[100];
while(1){
fgets(s, 100, stdin);
s[strlen(s)-1]='\0';
echolen = strlen(s);
/* send() from client; */
if (send(clientSocket, s, echolen, 0) != echolen)
{
printf("Failed");
}
if(strcmp(s,"exit") == 0) // check if exit is typed
exit(0);
fprintf(stdout, "Message from server: ");
while (received < echolen)
{
int bytes = 0;
/* recv() from server; */
if ((bytes = recv(clientSocket, buffer, echolen, 0)) < 1)
{
printf("Failed to get Information");
}
received += bytes;
buffer[bytes] = '\0';
fprintf(stdout, buffer);
}
int bytes = 0;
do {
buffer[bytes] = '\0';
printf("%s\n", buffer);
} while((bytes = recv(clientSocket, buffer, BUFFSIZE-1, 0))>=BUFFSIZE-1);
buffer[bytes] = '\0';
printf("%s\n", buffer);
printf("\n");
}
}
Server:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 4444
#define BUFFSIZE 2048
#define MAX 2048
void setup(char inputBuffer[], char *args[], int *background){
const char s[4] = " \t\n";
char *token;
token = strtok(inputBuffer, s);
int i = 0;
while(token != NULL){
args[i] = token;
i++;
token = strtok(NULL, s);
}
args[i] = NULL;
}
void HandleClient(int sock){
char buffer[BUFFSIZE];
int received = -1;
char data[MAX];
memset(data, 0, MAX);
while(1){
data[0] = '\0';
if((received = recv(sock, buffer, BUFFSIZE, 0)) < 0){
printf("Error");
}
buffer[received] = '\0';
strcat(data, buffer);
if(strcmp(data, "exit") == 0){
exit(0);
}
puts(data);
char *args[100];
setup(data, args, 0);
int pipefd[2], length;
if(pipe(pipefd)){
printf("failed to create pipe");
}
pid_t pid = fork();
char path[MAX];
if(pid==0)
{
close(pipefd[0]); // close the readonly side of the pipe
//close(1); // close the original stdout
dup2(pipefd[1],1); // duplicate pipfd[1] to stdout
dup2(pipefd[1], fileno(stderr));
//close(pipefd[0]); // close the readonly side of the pipe
close(pipefd[1]); // close the original write side of the pipe
printf("before execvp");
execvp(args[0],args); // finally execute the command
// exit(0);
}
else
if(pid>0)
{
close(pipefd[1]);
memset(path,'\0',MAX);
while(length=read(pipefd[0],path,MAX-1)){
//printf("Data read so far %s\n", path);
if(send(sock,path,strlen(path),0) != strlen(path) ){
printf("Failed");
}
fflush(NULL);
//printf("Data sent so far %s\n", path);
memset(path,0,MAX);
}
close(pipefd[0]);
//exit(1); removed so server will not terminate
}
else
{
printf("Error !\n");
exit(0);//
}
}
}
int main(){
int sockfd, ret;
struct sockaddr_in serverAddr;
int newSocket;
struct sockaddr_in newAddr;
socklen_t addr_size;
char buffer[1024];
pid_t childpid;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0){
printf("Error in connection.\n");
exit(1);
}
printf("Server Socket is created.\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(ret < 0){
printf("Error in binding");
exit(1);
}
printf("Bind to port %d\n", 4444);
if(listen(sockfd, 10) == 0){
printf("Listening....\n");
}else{
printf("Error in binding.\n");
}
while(1){
newSocket = accept(sockfd, (struct sockaddr*) &newAddr, &addr_size);
if(newSocket < 0){
exit(1);
}
printf("Connection accepted from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
//worker
if((childpid = fork()) == 0){
close(sockfd);
while(1){
recv(newSocket, buffer, 1024, 0);
if(strcmp(buffer, ":exit") == 0){
printf("Disconnected from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
break;
}else{
printf("Client: %s\n", buffer);
send(newSocket, buffer, strlen(buffer), 0);
bzero(buffer, sizeof(buffer));
}
HandleClient(newSocket);
}
}
}
close(newSocket);
return 0;
}

Sendto: invalid argument error

I'm creating a concurrent UDP socket for a university project. The client waits for a stdin command, then creates a new process and a new socket with the function child_job. The server receives the command from the client, creates a new process that initializes a new socket and then tries to send a string back to client. The problem is that the first sendto of the server create the error:
Invalid argument
I am not figuring out why. Can anyone help me please?
Code of the client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void child_job(int sockfd, struct sockaddr_in servaddr, char* buffer){
int n = sendto(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&servaddr, sizeof(servaddr));
if(n < 0){
perror("Error while sending roba to server\n");
exit(1);
}
printf("Connected to server\n");
char bufferaccio[128];
int length = sizeof(struct sockaddr);
int m = recvfrom(sockfd, bufferaccio, sizeof(bufferaccio), 0, (struct sockaddr*)&servaddr, (socklen_t *)&length);
if(m < 0){
perror("Error while receiving from server\n");
exit(1);
}
char stringa[128] = "I am a string from client";
m = sendto(sockfd, stringa, strlen(stringa), 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
if(m < 0){
perror("Error while sending stringa to server\n");
exit(1);
}
exit(1);
}
int main(int argc, char** argv){
int sockfd;
struct sockaddr_in str;
if(argc < 3){
fprintf(stderr, "Usage: %s portno ip\n", argv[0]);
exit(1);
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0){
perror("Error while creating socket\n");
exit(1);
}
memset((void*)&str, 0, sizeof(str));
str.sin_family = AF_INET;
str.sin_port = htons(atoi(argv[1]));
if(inet_pton(AF_INET, argv[2], &str.sin_addr)< 0){
perror("Error while inet_pton\n");
exit(1);
}
pid_t pid;
char buffer[128];
printf("Write something to send\n");
scanf("%s", buffer);
pid = fork();
if(pid == 0){
printf("I am a children with pid %d\n", getpid());
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0){
perror("Error while creating socket in the child process\n");
exit(1);
}
child_job(sockfd, str, buffer);
}else if(pid < 0){
perror("Error while creating child process\n");
exit(1);
}
wait(NULL);
exit(1);
}
Code of the server:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/types.h>
void initialize_newSocket(int* sock_fd, struct sockaddr_in *servaddr){
int sockfd;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0){
perror("Error while creating new socket\n");
exit(1);
}
int ret = bind(sockfd, (struct sockaddr *)servaddr, sizeof(*servaddr));
if(ret < 0){
perror("Error while binding in son\n");
exit(1);
}
*sock_fd = sockfd;
}
void child_server_job(){
struct sockaddr_in addr;
int sockfd;
memset((void *)&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(0);
initialize_newSocket(&sockfd, &addr);
char string[128] = "I am a string";
socklen_t fromlen = sizeof(addr);
int n = sendto(sockfd, string, strlen(string), 0, (struct sockaddr *)&addr, fromlen);
if(n < 0){
perror("Error while sending something\n");
exit(1);
}
int lenght = sizeof(struct sockaddr);
n = recvfrom(sockfd, string, strlen(string), 0, (struct sockaddr *)&addr, (socklen_t *)&lenght);
if(n < 0){
perror("Error while receveing data from client\n");
exit(1);
}
printf("I received this string %s\n", string);
exit(1);
}
int main(int argc, char** argv){
if(argc < 2){
fprintf(stderr, "Usage: %s portno\n", argv[0]);
exit(1);
}
int sockfd;
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0){
perror("Error while creating socket\n");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(argv[1]));
addr.sin_addr.s_addr = INADDR_ANY;
int retBind = bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
if(retBind < 0){
perror("Error while binding socket\n");
exit(1);
}
char bufferone[129];
int length = sizeof(struct sockaddr);
int n = recvfrom(sockfd, bufferone, sizeof(bufferone), 0, (struct sockaddr*)&addr, (socklen_t *)&length);
if(n < 0){
perror("Error while receiving roba from client\n");
exit(1);
}
printf("Printing: %s\n", bufferone);
pid_t pid = fork();
if(pid == 0){
printf("I am the child with pid %d\n", getpid());
child_server_job(sockfd, addr);
exit(1);
}else if(pid < 0){
perror("Error while forking new process\n");
exit(1);
}
wait(NULL);
exit(1);
}
Client output:
Write something to send
string
I am a children with pid 5756
Connected to server
Server output:
Printing: string
I am the child with pid 5757
Now it's my turn to send something
Error while sending something
: Invalid argument
The function "child_server_job" does not use passed parameters!
change the child_server_job to give parameter and use the passed parameters.
Edit
void child_server_job(){
struct sockaddr_in addr;
int sockfd;
memset((void *)&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(0);
initialize_newSocket(&sockfd, &addr);
To:
void child_server_job(int* sock_fd, struct sockaddr_in *servaddr){
struct sockaddr_in addr = *servaddr;
int sockfd = *sock_fd;
/*memset((void *)&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(0);
initialize_newSocket(&sockfd, &addr); */
AND
child_server_job(sockfd, addr);
To:
child_server_job(&sockfd, &addr);

how to initialize a buffer

This is my server/client sockets code.
I have a problem with the buffer, when the client receives the message from the server which is the buffer (i initialized it to "12") the output shows like this:
[+]Client Socket is created.
[+]Connected to Server.
Temp :
12121212121212121212121212121212121212121212121212121212121212121212121212121212
12121212121212�L��Q�
server :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 4444
int main(){
int sockfd, ret;
struct sockaddr_in serverAddr;
int clientSocket;
struct sockaddr_in newAddr;
socklen_t addr_size;
char buffer[1024];
char Temp[4]= "12";
pid_t childpid;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0){
printf("[-]Error in connection.\n");
exit(1);
}
printf("[+]Server Socket is created.\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(ret < 0){
printf("[-]Error in binding.\n");
exit(1);
}
printf("[+]Bind to port %d\n", 4444);
if(listen(sockfd, 10) == 0){
printf("[+]Listening....\n");
}else{
printf("[-]Error in binding.\n");
}
while(1){
clientSocket = accept(sockfd, (struct sockaddr*)&newAddr, &addr_size);
if(clientSocket < 0){
exit(1);
}
printf("Connection accepted from %s:%d\n", inet_ntoa(newAddr.sin_addr),
ntohs(newAddr.sin_port));
if((childpid = fork()) == 0){
close(sockfd);
while(1){
send(clientSocket, Temp, strlen(Temp), 0);
bzero(buffer, sizeof(buffer));
if(strcmp(Temp, ":exit") == 0){
printf("Disconnected from %s:%d\n",
inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
break;
}
}
}
}
return 0;
}
client :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 4444
int main(){
int clientSocket, ret;
struct sockaddr_in serverAddr;
char buffer[1024];
char Temp[4];
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if(clientSocket < 0){
printf("[-]Error in connection.\n");
exit(1);
}
printf("[+]Client Socket is created.\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = connect(clientSocket, (struct sockaddr*)&serverAddr,
sizeof(serverAddr));
if(ret < 0){
printf("[-]Error in connection.\n");
exit(1);
}
printf("[+]Connected to Server.\n");
bzero(buffer,512);
int words = 0;
char c;
while(1){
recv(clientSocket, Temp, 1024, 0);
if(recv(clientSocket, Temp, 1024, 0) < 0){
printf("[-]Error in receiving data.\n");
}
printf("Temp : %s \n",Temp);
if(strcmp(Temp, ":exit") == 0){
close(clientSocket);
printf("[-]Disconnected from server.\n");
} exit(1);
}
return 0;
}
Please, can anyone tell me how can I solve this problem, any help would be appreciated.
I see several problems with your client code:
char Temp[4];
...
recv(clientSocket, Temp, 1024, 0);
Here you are reading up to 1024 bytes into Temp although only 4 bytes are allocated for Temp. If you read more than 4 bytes thus other data structures will be filled with the read data, i.e. a classic buffer overflow.
printf("Temp : %s \n",Temp);
Here you are assuming that Temp is a \0 terminated string, which it is not. Therefore it will print out data starting with the position of &Temp up to a \0 byte it will find somewhere (way outside of Temp based on your output).
if(strcmp(Temp, ":exit") == 0){
Even though Temp is only 4 bytes this statement assumes at least 6 bytes (5 byte string and \0 for end of string marker).
Similar problems are also at the server code. Also strange is that your buffer variable is initialized but otherwise never used. My guess is that you originally wanted to use this instead of Temp for sending and receiving.

Issue using c sockets with threads to read from and write to the socket

I want to write a TCP server-client chat, but when I start the two threads for reading from and writing to a socket at both sides, I think they block each other out. Can anyone help me with this?
Server Code:
/* A simple server in the internet domain using TCP the port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
struct server_args_runner{
char buffer [256];
int newsockfd;
pthread_t tid;
pthread_attr_t attr;
//read/write attribute (read == 0 and write == 1)
int rw;
};
void error(char *msg){
perror(msg);
exit(1);
}
void* server_runner_fun(void* args){
// this is the chat part!
// get args:
int n;
struct server_args_runner *sar = (struct server_args_runner*) args;
if(sar->rw == 0){
printf("server thread trys to read from socket...\n");
//read-part
while(1){
bzero(sar->buffer, 256);
n = read(sar->newsockfd, sar->buffer, 255);
if (n < 0){
error("ERROR reading from socket");
}
}
printf("%s\n", sar->buffer);
} else {
printf("server thread trys to write to socket...\n");
//write-part
while(1){
bzero(sar->buffer, 256);
fgets(sar->buffer, 255, stdin);
n = write(sar->newsockfd, sar->buffer, strlen((char *) &(sar->buffer)));
if (n < 0){
error("ERROR writing to socket");
}
}
}
}
int main(int argc, char *argv[]){
//fd = filedescriptor
int sockfd, portno, clilen;
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2){
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
//socket(...) returns a descriptor
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1){
error("ERROR opening socket");
}
printf("Socket created successfully.\n");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
//htons(..) converts the short from hostbyteorder to networkbyteorder
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) == -1){
error("ERROR on binding");
}
printf("binding successfull on port %d\n", portno);
listen(sockfd, 2);
clilen = sizeof(cli_addr);
printf("server is listening ...\n");
struct server_args_runner server_write_t, server_read_t;
server_write_t.newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
printf("server accepted connection to client.\n");
if (server_write_t.newsockfd < 0){
error("ERROR on accept");
}
//initializing both server_threads
pthread_attr_init(&server_write_t.attr);
pthread_attr_init(&server_read_t.attr);
server_write_t.rw = 1;
server_read_t.rw = 0;
bcopy(&server_write_t.newsockfd, &server_read_t.newsockfd, sizeof(server_write_t.newsockfd));
pthread_create(&server_write_t.tid, &server_write_t.attr, server_runner_fun, &server_write_t);
pthread_create(&server_read_t.tid, &server_read_t.attr, server_runner_fun, &server_read_t);
pthread_join(server_write_t.tid, NULL);
pthread_join(server_read_t.tid, NULL);
return 0;
}
Client code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pthread.h>
struct client_args_runner{
char buffer [256];
int sockfd;
pthread_t tid;
pthread_attr_t attr;
//read/write attribute (read == 0 and write == 1)
int rw;
};
void error(char *msg){
perror(msg);
exit(0);
}
void* client_runner_fun(void* args){
// this is the chat part!
// get args:
int n;
struct client_args_runner *car = (struct client_args_runner*) args;
if(car->rw == 0){
printf("client thread trys to read from socket...\n");
//read-part
while(1){
bzero(car->buffer, 256);
n = read(car->sockfd, car->buffer, 255);
if (n < 0){
error("ERROR reading from socket");
}
}
printf("%s\n", car->buffer);
} else {
printf("client thread trys to write to socket...\n");
//write-part
while(1){
bzero(car->buffer, 256);
fgets(car->buffer, 255, stdin);
n = write(car->sockfd, car->buffer, strlen((char *) &(car->buffer)));
if (n < 0){
error("ERROR writing to socket");
}
}
}
}
int main(int argc, char *argv[]){
int portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
if (argc < 3){
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
struct client_args_runner client_write_t, client_read_t;
client_write_t.sockfd = socket(AF_INET, SOCK_STREAM, 0);
bcopy(&client_write_t.sockfd, &client_read_t.sockfd,
sizeof(client_write_t.sockfd));
if (client_write_t.sockfd == -1){
error("ERROR on creating socket_file_descriptor");
}
printf("socket created successfully.\n");
server = gethostbyname(argv[1]);
printf("hostname is valid.\n");
if(server == NULL){
fprintf(stderr, "Error, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *) server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
printf("before connecting to client..\n");
if (connect(client_write_t.sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) == -1){
error("ERROR connecting");
}
printf("client connected successfully to server.\n");
//initializing both client_threads
pthread_attr_init(&client_write_t.attr);
pthread_attr_init(&client_read_t.attr);
client_write_t.rw = 1;
client_read_t.rw = 0;
pthread_create(&client_write_t.tid, &client_write_t.attr, client_runner_fun, &client_write_t);
pthread_create(&client_read_t.tid, &client_read_t.attr, client_runner_fun, &client_read_t);
pthread_join(client_write_t.tid, NULL);
pthread_join(client_read_t.tid, NULL);
return 0;
}
Your printfs in both the client and server readers are outside the while(1) loops, so your client and server are communicating fine, you just aren't printing anything you read from the sockets.

Resources