6 #include <sys/socket.h>
11 #include <sys/types.h>
13 #include <arpa/inet.h>
14 #include <netinet/in.h>
17 #include <sys/ioctl.h>
19 #define MAX(a,b) ((a)>(b)?(a):(b))
21 /* open a socket to a tcp remote host with the specified port */
22 static int open_socket_out(const char *host, int port)
24 struct sockaddr_in sock_out;
29 res = socket(PF_INET, SOCK_STREAM, 0);
34 if (inet_pton(AF_INET, host, &addr) > 0) {
35 memcpy(&sock_out.sin_addr, &addr, sizeof(addr));
37 hp = gethostbyname(host);
39 fprintf(stderr,"tseal: unknown host %s\n", host);
42 memcpy(&sock_out.sin_addr, hp->h_addr, hp->h_length);
45 sock_out.sin_port = htons(port);
46 sock_out.sin_family = PF_INET;
48 if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out)) != 0) {
50 fprintf(stderr,"tseal: failed to connect to %s (%s)\n",
51 host, strerror(errno));
60 open a socket of the specified type, port and address for incoming data
62 int open_socket_in(int port)
64 struct sockaddr_in sock;
68 memset(&sock,0,sizeof(sock));
70 #ifdef HAVE_SOCK_SIN_LEN
71 sock.sin_len = sizeof(sock);
73 sock.sin_port = htons(port);
74 sock.sin_family = AF_INET;
76 res = socket(AF_INET, SOCK_STREAM, 0);
78 fprintf(stderr, "socket failed\n"); return -1;
82 setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
84 if (bind(res, (struct sockaddr *)&sock, sizeof(sock)) < 0) {
91 /* write to a file descriptor, making sure we get all the data out or
93 static void write_all(int fd, unsigned char *s, size_t n)
106 static void recv_send(int sock1, int sock2)
112 if (ioctl(sock1, FIONREAD, &num_ready) != 0
117 buf = malloc(num_ready);
119 len = read(sock1, buf, num_ready);
121 write_all(sock2, buf, len);
127 static void main_loop(int sock1, int sock2)
137 ret = select(MAX(sock1, sock2)+1, &fds, NULL, NULL, NULL);
138 if (ret == -1 && errno == EINTR) continue;
141 if (FD_ISSET(sock1, &fds)) {
142 recv_send(sock1, sock2);
145 if (FD_ISSET(sock2, &fds)) {
146 recv_send(sock2, sock1);
151 int main(int argc, char *argv[])
153 int listen_port, dest_port;
158 struct sockaddr addr;
159 socklen_t in_addrlen = sizeof(addr);
162 printf("Usage: tcpproxy <inport> <host> <port>\n");
166 listen_port = atoi(argv[1]);
168 dest_port = atoi(argv[3]);
170 listen_fd = open_socket_in(listen_port);
172 if (listen_fd == -1) {
173 fprintf(stderr,"listen on port %d failed - %s\n",
174 listen_port, strerror(errno));
178 if (listen(listen_fd, 5) == -1) {
179 fprintf(stderr,"listen failed\n");
183 signal(SIGCHLD, SIG_IGN);
185 while ((sock_in = accept(listen_fd,&addr,&in_addrlen)) != -1) {
188 sock_out = open_socket_out(host, dest_port);
189 if (sock_out == -1) {
193 main_loop(sock_in, sock_out);