#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 9000
#define HOST "127.0.0.1"
#define BUF_SIZE 2048
int cfd;
/* Signal Handler for SIGINT */
void sigintHandler(int sig_num) {
errno = 0;
if (fcntl(cfd, F_GETFD) != -1 || errno != EBADF) {
write(cfd, "exit\n", 6);
close(cfd);
}
printf("Terminating client\n");
fflush(stdout);
exit(-1);
}
static inline void die(const char *msg) {
perror(msg);
exit(-1);
}
int main() {
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(PORT),
.sin_addr.s_addr = inet_addr(HOST)
};
char buf[BUF_SIZE];
if ((cfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
die("Could not open socket");
if (connect(cfd, (struct sockaddr *) &addr, sizeof(addr)) < 0)
die("Could not connect to socket");
char *line = NULL;
size_t cap = 0;
__ssize_t length;
if (read(cfd, buf, BUF_SIZE) < 0)
die("Could not receive message");
printf("%s\n$> ", buf);
memset(buf, 0, BUF_SIZE);
while (1) {
//printf("[C] awaiting command\n");
if ((length = getline(&line, &cap, stdin)) < 0) {
fprintf(stderr, "Failed to read from STDIN");
fflush(stderr);
exit(-1);
}
if (strspn(line, " \n\t") == strlen(line)) {
// skip empty lines - empty being just spaces or tabs
continue;
}
strncpy(buf, line, strlen(line) + 1);
//printf("[C] pre send: \"%s\"\n", buf);
if (write(cfd, buf, strlen(line)) < 0)
die("Could not send message");
if (strcmp(line, "exit\n") == 0) {
free(line);
line = NULL;
break;
}
if (read(cfd, buf, BUF_SIZE) < 0)
die("Could not receive message");
printf("%s$> ", buf);
memset(buf, 0, BUF_SIZE);
free(line);
line = NULL;
}
close(cfd);
return 0;
}