|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <string.h> |
| 4 | +#include <sys/types.h> |
| 5 | +#include <sys/socket.h> |
| 6 | +#include <netinet/in.h> |
| 7 | + |
| 8 | +int to_sockaddr_in(char *ip, char *port, struct sockaddr_in *a) { |
| 9 | + a->sin_family = AF_INET; |
| 10 | + a->sin_port = htons(atoi(port)); |
| 11 | + a->sin_addr.s_addr = inet_addr(ip); |
| 12 | + return 0; |
| 13 | +} |
| 14 | + |
| 15 | +int parse_address(char *s, struct sockaddr_in *a) { |
| 16 | + int ret = 0; |
| 17 | + char *c = strrchr(s,':'); |
| 18 | + if (c) { |
| 19 | + *c = 0; |
| 20 | + ret = to_sockaddr_in(s,c+1,a); |
| 21 | + *c = ':'; |
| 22 | + } else { |
| 23 | + ret = 1; |
| 24 | + } |
| 25 | + return ret; |
| 26 | +} |
| 27 | + |
| 28 | + |
| 29 | +int main(int argc, char **argv) { |
| 30 | + if ( argc < 3 ) { |
| 31 | + printf("usage: udp_relay <source> <dest1> [ <dest2> ... ]\n"); |
| 32 | + exit(1); |
| 33 | + } |
| 34 | + |
| 35 | + struct sockaddr_in s; |
| 36 | + struct sockaddr_in d[10]; |
| 37 | + int dcount = 0, i; |
| 38 | + |
| 39 | + if ( parse_address(argv[1],&s) ) { |
| 40 | + printf("error: could not resolve source address: %s\n",argv[1]); |
| 41 | + return 1; |
| 42 | + } |
| 43 | + |
| 44 | + for (i=2;i<argc&&dcount<10;i++) { |
| 45 | + if ( parse_address(argv[i],&d[dcount]) ) { |
| 46 | + printf("error: could not resolve destination address: %s\n",argv[i]); |
| 47 | + return 1; |
| 48 | + } |
| 49 | + dcount++; |
| 50 | + } |
| 51 | + |
| 52 | + int sock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP); |
| 53 | + if ( sock < 0 ) { |
| 54 | + perror("socket()"); |
| 55 | + return 1; |
| 56 | + } |
| 57 | + if ( bind(sock,(struct sockaddr*)&s,sizeof(s)) ) { |
| 58 | + perror("bind()"); |
| 59 | + return 1; |
| 60 | + } |
| 61 | + |
| 62 | + |
| 63 | + char buffer[65536]; |
| 64 | + while (1) { |
| 65 | + int n = recv(sock,buffer,sizeof(buffer),0); |
| 66 | + if ( n < 0 ) continue; |
| 67 | + printf("got packet: length=%d\n",n); |
| 68 | + for (i=0;i<dcount;i++) { |
| 69 | + sendto(sock,buffer,n,0,(struct sockaddr*)&d[i],sizeof(d[i])); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return 0; |
| 74 | +} |
0 commit comments