#include #include #include #include #include #include #include #include int redirect_stdio_to_socket(char *target) { int fd = connect_socket(target); if(fd<0)return -1; close(0); close(1); dup2(fd, 0); dup2(fd, 1); return 0; } struct in_addr lookup_host(char *host) { struct in_addr addr; struct hostent *he; if(inet_aton(host, &addr))return addr; he = gethostbyname(host); if(!he) { fprintf(stderr, "unable to find host `%s'\n", host); exit(-1); } if(he->h_addrtype != AF_INET) { fprintf(stderr, "`%s' is not an internet host\n", host); exit(-1); } if(he->h_length != sizeof(struct in_addr)) { fprintf(stderr, "`%s' address is not an IPv4 address\n", host); exit(-1); } addr = *(struct in_addr*)he->h_addr; return addr; } struct sockaddr_in make_address(char *host, int port) { struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons((short)port); addr.sin_addr.s_addr = (lookup_host(host).s_addr); //printf("target %s : %d\n", inet_ntoa(addr.sin_addr), port); return addr; } int connect_socket(char *target) { char *host, *portstr; int port, fd; struct sockaddr_in addr; host = target; portstr = strchr(target, ':'); if(!portstr) { // should we have a default port? invalid: fprintf(stderr, "invalid host/port specification `%s'\n", target); fprintf(stderr, " should be of the form: host:port\n"); exit(-1); } port = atoi(portstr+1); if(port==0)goto invalid; *portstr=0; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(fd<0) { perror("socket"); exit(-1); } addr = make_address(host, port); *portstr=':'; if(connect(fd, (struct sockaddr*)&addr, sizeof(addr))) { perror("connect"); close(fd); return -1; } return fd; }