8 #include <sys/socket.h>
13 #include <sys/types.h>
15 #include <arpa/inet.h>
16 #include <netinet/in.h>
18 static void get_address(const char *host, struct in_addr *addr)
20 if (inet_pton(AF_INET, host, addr) <= 0) {
22 hp = gethostbyname(host);
24 fprintf(stderr,"unknown host %s\n", host);
27 memcpy(addr, hp->h_addr, hp->h_length);
32 open a socket of the specified type, port and address for incoming data
34 int open_socket_in(int port)
36 struct sockaddr_in sock;
40 memset(&sock,0,sizeof(sock));
42 #ifdef HAVE_SOCK_SIN_LEN
43 sock.sin_len = sizeof(sock);
45 sock.sin_port = htons(port);
46 sock.sin_family = AF_INET;
48 res = socket(AF_INET, SOCK_DGRAM, 0);
50 fprintf(stderr, "socket failed\n"); return -1;
54 setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
56 if (bind(res, (struct sockaddr *)&sock, sizeof(sock)) < 0) {
63 static void main_loop(int sock, const char *host1, const char *host2)
65 unsigned char buf[10240];
66 struct in_addr addr1, addr2;
68 get_address(host1, &addr1);
69 get_address(host2, &addr2);
79 ret = select(sock, &fds, NULL, NULL, NULL);
80 if (ret == -1 && errno == EINTR) continue;
83 if (FD_ISSET(sock, &fds)) {
84 static struct sockaddr_in from;
85 static socklen_t fromlen = sizeof(from);
86 int n = recvfrom(sock, buf, sizeof(buf), 0,
87 (struct sockaddr *)&from, &fromlen);
90 if (from.sin_addr.s_addr == addr1.s_addr) {
92 } else if (from.sin_addr.s_addr == addr2.s_addr) {
95 printf("Unexpected packet from %s\n", inet_ntoa(from.sin_addr));
99 from.sin_addr = *addr;
100 ret = sendto(sock, buf, n, 0, (struct sockaddr *)&from, sizeof(from));
102 printf("Failed to send %d bytes to %s - %d\n",
103 n, inet_ntoa(*addr), ret);
109 int main(int argc, char *argv[])
116 printf("Usage: udpproxy <port> <host1> <host2>\n");
120 listen_port = atoi(argv[1]);
124 sock_in = open_socket_in(listen_port);
126 fprintf(stderr,"sock on port %d failed - %s\n",
127 listen_port, strerror(errno));
131 main_loop(sock_in, host1, host2);