udp_proxy_server.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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] = "127.0.0.1";
  13. static int proxy_port = 1234;
  14. // hloop_create_udp_server -> hio_setup_udp_upstream
  15. int main(int argc, char** argv) {
  16. if (argc < 3) {
  17. printf("Usage: %s port proxy_host:proxy_port\n", argv[0]);
  18. return -10;
  19. }
  20. int port = atoi(argv[1]);
  21. char* pos = strchr(argv[2], ':');
  22. if (pos) {
  23. int len = pos - argv[2];
  24. if (len > 0) {
  25. memcpy(proxy_host, argv[2], len);
  26. proxy_host[len] = '\0';
  27. }
  28. proxy_port = atoi(pos + 1);
  29. } else {
  30. strncpy(proxy_host, argv[2], sizeof(proxy_host));
  31. }
  32. printf("proxy: [%s:%d]\n", proxy_host, proxy_port);
  33. hloop_t* loop = hloop_new(0);
  34. hio_t* io = hloop_create_udp_server(loop, "0.0.0.0", port);
  35. if (io == NULL) {
  36. return -20;
  37. }
  38. hio_t* upstream_io = hio_setup_udp_upstream(io, proxy_host, proxy_port);
  39. if (upstream_io == NULL) {
  40. return -30;
  41. }
  42. hloop_run(loop);
  43. hloop_free(&loop);
  44. return 0;
  45. }