udp_proxy_server.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * udp proxy server
  3. *
  4. * @build: make examples
  5. * @udp_server: bin/udp_echo_server 1234
  6. * @proxy_server: bin/udp_proxy_server 2222 127.0.0.1:1234
  7. * @client: bin/nc -u 127.0.0.1 2222
  8. * > hello
  9. * < hello
  10. */
  11. #include "hloop.h"
  12. static char proxy_host[64] = "0.0.0.0";
  13. static int proxy_port = 1080;
  14. static char backend_host[64] = "127.0.0.1";
  15. static int backend_port = 80;
  16. // hloop_create_udp_server -> hio_setup_udp_upstream
  17. int main(int argc, char** argv) {
  18. if (argc < 3) {
  19. printf("Usage: %s proxy_port backend_host:backend_port\n", argv[0]);
  20. return -10;
  21. }
  22. proxy_port = atoi(argv[1]);
  23. char* pos = strchr(argv[2], ':');
  24. if (pos) {
  25. int len = pos - argv[2];
  26. if (len > 0) {
  27. memcpy(backend_host, argv[2], len);
  28. backend_host[len] = '\0';
  29. }
  30. backend_port = atoi(pos + 1);
  31. } else {
  32. strncpy(backend_host, argv[2], sizeof(backend_host));
  33. }
  34. printf("%s:%d proxy %s:%d\n", proxy_host, proxy_port, backend_host, backend_port);
  35. hloop_t* loop = hloop_new(0);
  36. hio_t* io = hloop_create_udp_server(loop, proxy_host, proxy_port);
  37. if (io == NULL) {
  38. return -20;
  39. }
  40. hio_t* upstream_io = hio_setup_udp_upstream(io, backend_host, backend_port);
  41. if (upstream_io == NULL) {
  42. return -30;
  43. }
  44. hloop_run(loop);
  45. hloop_free(&loop);
  46. return 0;
  47. }