inet_pton.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <sys/socket.h>
  2. #include <arpa/inet.h>
  3. #include <ctype.h>
  4. #include <errno.h>
  5. #include <string.h>
  6. static int hexval(unsigned c)
  7. {
  8. if (c-'0'<10) return c-'0';
  9. c |= 32;
  10. if (c-'a'<6) return c-'a'+10;
  11. return -1;
  12. }
  13. int inet_pton(int af, const char *restrict s, void *restrict a0)
  14. {
  15. uint16_t ip[8];
  16. unsigned char *a = a0;
  17. int i, j, v, d, brk=-1, need_v4=0;
  18. if (af==AF_INET) {
  19. for (i=0; i<4; i++) {
  20. for (v=j=0; j<3 && isdigit(s[j]); j++)
  21. v = 10*v + s[j]-'0';
  22. if (j==0 || (j>1 && s[0]=='0') || v>255) return 0;
  23. a[i] = v;
  24. if (s[j]==0 && i==3) return 1;
  25. if (s[j]!='.') return 0;
  26. s += j+1;
  27. }
  28. return 0;
  29. } else if (af!=AF_INET6) {
  30. errno = EAFNOSUPPORT;
  31. return -1;
  32. }
  33. if (*s==':' && *++s!=':') return 0;
  34. for (i=0; ; i++) {
  35. if (s[0]==':' && brk<0) {
  36. brk=i;
  37. ip[i]=0;
  38. if (!*++s) break;
  39. continue;
  40. }
  41. for (v=j=0; j<4 && (d=hexval(s[j]))>=0; j++)
  42. v=16*v+d;
  43. if (j==0) return 0;
  44. ip[i] = v;
  45. if (!s[j] && (brk>=0 || i==7)) break;
  46. if (i==7) return 0;
  47. if (s[j]!=':') {
  48. if (s[j]!='.' || (i<6 && brk<0)) return 0;
  49. need_v4=1;
  50. i++;
  51. break;
  52. }
  53. s += j+1;
  54. }
  55. if (brk>=0) {
  56. memmove(ip+brk+7-i, ip+brk, 2*(i+1-brk));
  57. for (j=0; j<7-i; j++) ip[brk+j] = 0;
  58. }
  59. for (j=0; j<8; j++) {
  60. *a++ = ip[j]>>8;
  61. *a++ = ip[j];
  62. }
  63. if (need_v4 && inet_pton(AF_INET, (void *)s, a-4) <= 0) return 0;
  64. return 1;
  65. }