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)
104 static void randomise(char *buf, int n)
107 if (random() % 100 < 70) {
111 buf[random() % n] = random();
115 static void main_loop(int sock1, int sock2)
117 unsigned char buf[1024];
129 ret = select(MAX(sock1, sock2)+1, &fds, NULL, NULL, NULL);
130 if (ret == -1 && errno == EINTR) continue;
133 if (FD_ISSET(sock1, &fds)) {
134 int n = read(sock1, buf, sizeof(buf));
137 // randomise(buf, n);
139 write_all(sock2, buf, n);
142 if (FD_ISSET(sock2, &fds)) {
143 int n = read(sock2, buf, sizeof(buf));
145 write_all(sock1, buf, n);
150 int main(int argc, char *argv[])
152 int listen_port, dest_port;
157 struct sockaddr addr;
158 int in_addrlen = sizeof(addr);
161 printf("Usage: sockspy <inport> <host> <port>\n");
165 listen_port = atoi(argv[1]);
167 dest_port = atoi(argv[3]);
169 listen_fd = open_socket_in(listen_port);
171 if (listen_fd == -1) {
172 fprintf(stderr,"listen on port %d failed - %s\n",
173 listen_port, strerror(errno));
177 if (listen(listen_fd, 100) == -1) {
178 fprintf(stderr,"listen failed\n");
183 sock_in = accept(listen_fd,&addr,&in_addrlen);
185 fprintf(stderr,"accept on port %d failed - %s\n",
186 listen_port, strerror(errno));
193 sock_out = open_socket_out(host, dest_port);
194 if (sock_out == -1) {
198 main_loop(sock_in, sock_out);