lib_udp.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * udp_lib.c - routines for managing UDP connections
  3. *
  4. * %W% %G%
  5. *
  6. * Copyright (c) 1994 Larry McVoy.
  7. */
  8. #define _LIB /* bench.h needs this */
  9. #include "bench.h"
  10. /*
  11. * Get a UDP socket, bind it, figure out the port,
  12. * and advertise the port as program "prog".
  13. *
  14. * XXX - it would be nice if you could advertise ascii strings.
  15. */
  16. int
  17. udp_server(u_long prog, int rdwr)
  18. {
  19. int sock;
  20. struct sockaddr_in s;
  21. if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
  22. perror("socket");
  23. exit(1);
  24. }
  25. sock_optimize(sock, rdwr);
  26. bzero((void*)&s, sizeof(s));
  27. s.sin_family = AF_INET;
  28. #ifdef NO_PORTMAPPER
  29. s.sin_port = htons(prog);
  30. #endif
  31. if (bind(sock, (struct sockaddr*)&s, sizeof(s)) < 0) {
  32. perror("bind");
  33. exit(2);
  34. }
  35. #ifndef NO_PORTMAPPER
  36. (void)pmap_unset(prog, (u_long)1);
  37. if (!pmap_set(prog, (u_long)1, (u_long)IPPROTO_UDP,
  38. (unsigned short)sockport(sock))) {
  39. perror("pmap_set");
  40. exit(5);
  41. }
  42. #endif
  43. return (sock);
  44. }
  45. /*
  46. * Unadvertise the socket
  47. */
  48. void
  49. udp_done(int prog)
  50. {
  51. (void)pmap_unset((u_long)prog, (u_long)1);
  52. }
  53. /*
  54. * "Connect" to the UCP socket advertised as "prog" on "host" and
  55. * return the connected socket.
  56. */
  57. int
  58. udp_connect(char *host, u_long prog, int rdwr)
  59. {
  60. struct hostent *h;
  61. struct sockaddr_in sin;
  62. int sock;
  63. u_short port;
  64. if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
  65. perror("socket");
  66. exit(1);
  67. }
  68. sock_optimize(sock, rdwr);
  69. if (!(h = gethostbyname(host))) {
  70. perror(host);
  71. exit(2);
  72. }
  73. bzero((void *) &sin, sizeof(sin));
  74. sin.sin_family = AF_INET;
  75. bcopy((void*)h->h_addr, (void *) &sin.sin_addr, h->h_length);
  76. #ifdef NO_PORTMAPPER
  77. sin.sin_port = htons(prog);
  78. #else
  79. port = pmap_getport(&sin, prog, (u_long)1, IPPROTO_UDP);
  80. if (!port) {
  81. perror("lib UDP: No port found");
  82. exit(3);
  83. }
  84. sin.sin_port = htons(port);
  85. #endif
  86. if (connect(sock, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
  87. perror("connect");
  88. exit(4);
  89. }
  90. return (sock);
  91. }