getprotobyname.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. /* bsd extensions */
  10. #include <sys/uio.h>
  11. #include <sys/socket.h>
  12. #include <netinet/in.h>
  13. #include <netdb.h>
  14. #include "priv.h"
  15. extern int h_errno;
  16. enum
  17. {
  18. Nname= 6,
  19. };
  20. static struct protoent r;
  21. struct protoent *getprotobyname(const char *name) {
  22. int fd, i, m;
  23. char *p, *bp;
  24. int nn, na;
  25. unsigned long x;
  26. static char buf[1024], proto[1024];
  27. static char *nptr[Nname+1];
  28. /* connect to server */
  29. fd = open("/net/cs", O_RDWR);
  30. if(fd < 0){
  31. _syserrno();
  32. h_errno = NO_RECOVERY;
  33. return 0;
  34. }
  35. /* construct the query, always expect a protocol# back */
  36. sprintf(buf, "!protocol=%s ipv4proto=*", name);
  37. /* query the server */
  38. if(write(fd, buf, strlen(buf)) < 0){
  39. _syserrno();
  40. h_errno = TRY_AGAIN;
  41. return 0;
  42. }
  43. lseek(fd, 0, 0);
  44. for(i = 0; i < sizeof(buf)-1; i += m){
  45. m = read(fd, buf+i, sizeof(buf) - 1 - i);
  46. if(m <= 0)
  47. break;
  48. buf[i+m++] = ' ';
  49. }
  50. close(fd);
  51. buf[i] = 0;
  52. /* parse the reply */
  53. nn = na = 0;
  54. for(bp = buf;;){
  55. p = strchr(bp, '=');
  56. if(p == 0)
  57. break;
  58. *p++ = 0;
  59. if(strcmp(bp, "protocol") == 0){
  60. if(!nn)
  61. r.p_name = p;
  62. if(nn < Nname)
  63. nptr[nn++] = p;
  64. } else if(strcmp(bp, "ipv4proto") == 0){
  65. r.p_proto = atoi(p);
  66. na++;
  67. }
  68. while(*p && *p != ' ')
  69. p++;
  70. if(*p)
  71. *p++ = 0;
  72. bp = p;
  73. }
  74. nptr[nn] = 0;
  75. r.p_aliases = nptr;
  76. if (nn+na == 0)
  77. return 0;
  78. return &r;
  79. }