#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <ctype.h>
#define BUFLEN 1024
volatile static int run = 1;
void sendx(int sd) {
int sent, i;
char buffer[BUFLEN], ch;
do {
i = 0;
do {
ch = getc(stdin);
buffer[i] = ch;
i++;
} while (ch != '\n' && i < BUFLEN);
sent = write(sd, buffer, i);
} while (sent == i && run);
}
void recvx(int sd) {
const char nothing[] = { '?' };
int len, i;
char buffer[BUFLEN];
do {
len = read(sd, buffer, BUFLEN);
i = 0;
while (i < len) {
if (isprint(buffer[i]))
write(1, buffer + i, 1);
else write(1, nothing, 1);
i++;
}
} while (len > 0 && run);
close(sd);
nothing[0] = '\n';
write(0, nothing, 1);
fflush(stdin);
}
int main(int argc, char **argv) {
int sd, pid;
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr));
assert(argc == 3);
sd = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
assert(inet_pton(AF_INET, argv[1], &addr.sin_addr) > 0);
addr.sin_port = htons(atoi(argv[2]));
assert(sd > -1);
assert(connect(sd, (struct sockaddr *)&addr, sizeof(addr)) > -1);
pid = fork();
assert(pid > -1);
if (pid == 0) sendx(sd);
else recvx(sd);
run = 0;
return 0;
}