6 #include <sys/socket.h>
11 #include <sys/types.h>
13 #include <arpa/inet.h>
14 #include <netinet/in.h>
16 #define MAX(a,b) ((a)>(b)?(a):(b))
18 /* open a socket to a tcp remote host with the specified port */
19 static int open_socket_out(const char *host, int port)
21 struct sockaddr_in sock_out;
26 res = socket(PF_INET, SOCK_STREAM, 0);
31 if (inet_pton(AF_INET, host, &addr) > 0) {
32 memcpy(&sock_out.sin_addr, &addr, sizeof(addr));
34 hp = gethostbyname(host);
36 fprintf(stderr,"unknown host %s\n", host);
39 memcpy(&sock_out.sin_addr, hp->h_addr, hp->h_length);
42 sock_out.sin_port = htons(port);
43 sock_out.sin_family = PF_INET;
45 if (connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out)) != 0) {
47 fprintf(stderr,"failed to connect to %s (%s)\n",
48 host, strerror(errno));
57 open a socket of the specified type, port and address for incoming data
59 int open_socket_in(int port)
61 struct sockaddr_in sock;
65 memset(&sock,0,sizeof(sock));
67 #ifdef HAVE_SOCK_SIN_LEN
68 sock.sin_len = sizeof(sock);
70 sock.sin_port = htons(port);
71 sock.sin_family = AF_INET;
73 res = socket(AF_INET, SOCK_STREAM, 0);
75 fprintf(stderr, "socket failed\n"); return -1;
79 setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
81 if (bind(res, (struct sockaddr *)&sock, sizeof(sock)) < 0) {
88 /* write to a file descriptor, making sure we get all the data out or
90 static void write_all(int fd, unsigned char *s, size_t n)
103 static void main_loop(int sock1, int sock2)
105 unsigned char buf[1024];
117 ret = select(MAX(sock1, sock2)+1, &fds, NULL, NULL, NULL);
118 if (ret == -1 && errno == EINTR) continue;
121 if (FD_ISSET(sock1, &fds)) {
122 int n = read(sock1, buf, sizeof(buf));
125 write_all(sock2, buf, n);
128 if (FD_ISSET(sock2, &fds)) {
129 int n = read(sock2, buf, sizeof(buf));
131 write_all(sock1, buf, n);
136 int main(int argc, char *argv[])
138 int listen_port, dest_port;
143 struct sockaddr addr;
144 int in_addrlen = sizeof(addr);
147 printf("Usage: sockspy <inport> <host> <port>\n");
151 listen_port = atoi(argv[1]);
153 dest_port = atoi(argv[3]);
155 listen_fd = open_socket_in(listen_port);
157 if (listen_fd == -1) {
158 fprintf(stderr,"listen on port %d failed - %s\n",
159 listen_port, strerror(errno));
163 if (listen(listen_fd, 100) == -1) {
164 fprintf(stderr,"listen failed\n");
169 sock_in = accept(listen_fd,&addr,&in_addrlen);
171 fprintf(stderr,"accept on port %d failed - %s\n",
172 listen_port, strerror(errno));
179 sock_out = open_socket_out(host, dest_port);
180 if (sock_out == -1) {
184 main_loop(sock_in, sock_out);