#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <termios.h> #include <string.h> #define DO 0xfd #define WONT 0xfc #define WILL 0xfb #define DONT 0xfe #define CMD 0xff #define CMD_ECHO 1 #define CMD_WINDOW_SIZE 31 #define IAC 255 #define SB 250 #define SE 240 #define BUFLEN 200 #define ESCAPE 27 #define SA struct sockaddr static struct termios tin; static void terminal_set(void); static void terminal_reset(void); void negotiate(int sock, unsigned char *buf, int len); void connect_to_server(int sock, int port, char *address); int main(int argc, char *argv[]) { int sock; unsigned char buf[BUFLEN + 1]; int len; int i; int port = 23; if (argc < 2 || argc > 3) { printf("Usage: %s address [port] ", argv[0]); return 1; } if (argc == 3) port = atoi(argv[2]); // Create socket sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { perror("Could not create socket. Error"); return 1; } printf("Trying %s... ", argv[1]); connect_to_server(sock, port, argv[1]); printf("Connected to %s ", argv[1]); puts("Escape character is '^]'."); // set terminal terminal_set(); atexit(terminal_reset); // 1 second struct timeval ts; ts.tv_sec = 1; ts.tv_usec = 0; while (1) { // select setup fd_set fds; FD_ZERO(&fds); if (sock != 0) FD_SET(sock, &fds); FD_SET(0, &fds); // wait for data int nready = select(sock + 1, &fds, (fd_set *) 0, (fd_set *) 0, &ts); if (nready < 0) { perror("select. Error"); return 1; } else if (nready == 0) { ts.tv_sec = 1; ts.tv_usec = 0; } else if (sock != 0 && FD_ISSET(sock, &fds)) { // start by reading a single byte int rv; if ((rv = recv(sock, buf, 1, 0)) < 0) return 1; else if (rv == 0) { printf("Connection closed by the remote end "); return 0; } if (buf[0] == CMD) { // read 2 more bytes len = recv(sock, buf + 1, 2, 0); if (len < 0) return 1; else if (len == 0) { printf("Connection closed by the remote end "); return 0; } negotiate(sock, buf, 3); } else { len = 1; buf[len] = '