1
0

inet_ntop.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include <sys/socket.h>
  2. #include <netinet/in.h>
  3. #include <arpa/inet.h>
  4. #include <netdb.h>
  5. #include <errno.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8. const char *inet_ntop(int af, const void *a0, char *s, socklen_t l)
  9. {
  10. const unsigned char *a = a0;
  11. int i, j, max, best;
  12. char buf[100];
  13. switch (af) {
  14. case AF_INET:
  15. if (snprintf(s, l, "%d.%d.%d.%d", a[0],a[1],a[2],a[3]) < l)
  16. return s;
  17. break;
  18. case AF_INET6:
  19. memset(buf, 'x', sizeof buf);
  20. buf[sizeof buf-1]=0;
  21. snprintf(buf, sizeof buf,
  22. "%x:%x:%x:%x:%x:%x:%x:%x",
  23. 256*a[0]+a[1],256*a[2]+a[3],
  24. 256*a[4]+a[5],256*a[6]+a[7],
  25. 256*a[8]+a[9],256*a[10]+a[11],
  26. 256*a[12]+a[13],256*a[14]+a[15]);
  27. /* Replace longest /(^0|:)[:0]{2,}/ with "::" */
  28. for (i=best=0, max=2; buf[i]; i++) {
  29. if (i && buf[i] != ':') continue;
  30. j = strspn(buf+i, ":0");
  31. if (j>max) best=i, max=j;
  32. }
  33. if (max>2) {
  34. buf[best] = buf[best+1] = ':';
  35. strcpy(buf+best+2, buf+best+max);
  36. }
  37. if (strlen(buf) < l) {
  38. strcpy(s, buf);
  39. return s;
  40. }
  41. break;
  42. default:
  43. errno = EAFNOSUPPORT;
  44. return 0;
  45. }
  46. errno = ENOSPC;
  47. return 0;
  48. }