getservbyname.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /* posix */
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <fcntl.h>
  7. #include <string.h>
  8. #include <errno.h>
  9. #include <ctype.h>
  10. /* bsd extensions */
  11. #include <sys/uio.h>
  12. #include <sys/socket.h>
  13. #include <netinet/in.h>
  14. #include <netdb.h>
  15. #include "priv.h"
  16. enum
  17. {
  18. Nname= 6,
  19. };
  20. /*
  21. * for inet addresses only
  22. */
  23. struct servent*
  24. getservbyname(char *name, char *proto)
  25. {
  26. int i, fd, m, num;
  27. char *p, *bp;
  28. int nn, na;
  29. static struct servent s;
  30. static char buf[1024];
  31. static char *nptr[Nname+1];
  32. num = 1;
  33. for(p = name; *p; p++)
  34. if(!isdigit(*p))
  35. num = 0;
  36. s.s_name = 0;
  37. /* connect to server */
  38. fd = open("/net/cs", O_RDWR);
  39. if(fd < 0){
  40. _syserrno();
  41. return 0;
  42. }
  43. /* construct the query, always expect an ip# back */
  44. if(num)
  45. snprintf(buf, sizeof buf, "!port=%s %s=*", name, proto);
  46. else
  47. snprintf(buf, sizeof buf, "!%s=%s port=*", proto, name);
  48. /* query the server */
  49. if(write(fd, buf, strlen(buf)) < 0){
  50. _syserrno();
  51. return 0;
  52. }
  53. lseek(fd, 0, 0);
  54. for(i = 0; i < sizeof(buf)-1; i += m){
  55. m = read(fd, buf+i, sizeof(buf) - 1 - i);
  56. if(m <= 0)
  57. break;
  58. buf[i+m++] = ' ';
  59. }
  60. close(fd);
  61. buf[i] = 0;
  62. /* parse the reply */
  63. nn = na = 0;
  64. for(bp = buf;;){
  65. p = strchr(bp, '=');
  66. if(p == 0)
  67. break;
  68. *p++ = 0;
  69. if(strcmp(bp, proto) == 0){
  70. if(nn < Nname)
  71. nptr[nn++] = p;
  72. } else if(strcmp(bp, "port") == 0){
  73. s.s_port = htons(atoi(p));
  74. }
  75. while(*p && *p != ' ')
  76. p++;
  77. if(*p)
  78. *p++ = 0;
  79. bp = p;
  80. }
  81. if(nn+na == 0)
  82. return 0;
  83. nptr[nn] = 0;
  84. s.s_aliases = nptr;
  85. if(s.s_name == 0)
  86. s.s_name = nptr[0];
  87. return &s;
  88. }