8 #include <sys/socket.h>
13 #include <sys/types.h>
15 #include <arpa/inet.h>
16 #include <netinet/in.h>
19 #define MAX(a,b) ((a)>(b)?(a):(b))
21 /* open a socket to a 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_DGRAM, 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,"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,"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_DGRAM, 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)
107 static void main_loop(int sock1, int sock2)
109 unsigned char buf[10240];
111 static struct sockaddr from;
112 static socklen_t fromlen = sizeof(from);
122 ret = select(MAX(sock1, sock2)+1, &fds, NULL, NULL, NULL);
123 if (ret == -1 && errno == EINTR) continue;
126 if (FD_ISSET(sock1, &fds)) {
127 int n = recvfrom(sock1, buf, sizeof(buf), 0, &from, &fromlen);
130 // printf("out %d bytes\n", n);
131 write_all(sock2, buf, n);
134 if (FD_ISSET(sock2, &fds)) {
135 int n = read(sock2, buf, sizeof(buf));
138 // printf("in %d bytes\n", n);
139 sendto(sock1, buf, n, 0, &from, fromlen);
144 static int sig_alrm(int sig)
149 int main(int argc, char *argv[])
151 int listen_port, dest_port;
155 struct sockaddr addr;
156 int in_addrlen = sizeof(addr);
160 printf("Usage: sockspy <inport> <host> <port>\n");
164 listen_port = atoi(argv[1]);
166 dest_port = atoi(argv[3]);
168 sock_in = open_socket_in(listen_port);
171 fprintf(stderr,"sock on port %d failed - %s\n",
172 listen_port, strerror(errno));
176 signal(SIGCHLD, SIG_IGN);
178 signal(SIGALRM, sig_alrm);
180 sock_out = open_socket_out(host, dest_port);
182 main_loop(sock_in, sock_out);