#include #include #include #include #include #include #include #include #include #include #include #include #define PORT "2345" #define UP "\x1b[A" void error(char *msg) { perror(msg); exit(1); } void readsocket(FILE * sock) { char buffer[256]; while (1) { if (!fgets(buffer, sizeof(buffer), sock)) break; fputs(buffer, stdout); fflush(stdout); } fclose(sock); } void writesocket(FILE * sock, char nick[]) { char buffer[256]; fflush(stderr); fprintf(sock, "nick: %s\n\n", nick); fflush(sock); while (fgets(buffer, sizeof(buffer), stdin)) { fprintf(stderr, UP); fputs(buffer, sock); fflush(sock); } fclose(sock); } int main(int argc, char *argv[]) { int sockfd; //, portno; //struct sockaddr_in serv_addr; struct addrinfo *res, hints, *p; // struct hostent *server; char *host, *nick; /* * struct hostent { char *h_name; official name of host char **h_aliases; alias list int h_addrtype; host address type int h_length; length of address char **h_addr_list; list of addresses from name server #define h_addr h_addr_list[0] address, for backward compatiblity }; */ if (argc < 2) { fprintf(stderr, "usage: chat nick [host]\n"); exit(1); } nick = argv[1]; host = argv[2]; if (!host) host = "127.0.0.1"; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; int result = getaddrinfo(host, PORT, &hints, &res); if (result != 0) error("ERROR getaddrinfo\n"); for (p = res; p; p = p->ai_next) { sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (sockfd < 0) continue; if (connect(sockfd, p->ai_addr, p->ai_addrlen) < 0) error("ERROR connecting"); break; } FILE *io = fdopen(sockfd, "r+"); pid_t pid; pid = fork(); if (pid < 0) { perror("ERROR from fork()"); } else if (pid == 0) { readsocket(io); kill(getppid(), SIGTERM); } else { writesocket(io, nick); kill(pid, SIGTERM); waitpid(pid, NULL, 0); } return 0; }