gn_ipv46.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "gai_hdr.h"
  2. /*
  3. * Handle either an IPv4 or an IPv6 address and port.
  4. */
  5. /* include gn_ipv46 */
  6. int
  7. gn_ipv46(char *host, size_t hostlen, char *serv, size_t servlen,
  8. void *aptr, size_t alen, int family, int port, int flags)
  9. {
  10. char *ptr;
  11. struct hostent *hptr;
  12. struct servent *sptr;
  13. if (hostlen > 0) {
  14. if (flags & NI_NUMERICHOST) {
  15. if (inet_ntop(family, aptr, host, hostlen) == NULL)
  16. return(1);
  17. } else {
  18. hptr = gethostbyaddr(aptr, alen, family);
  19. if (hptr != NULL && hptr->h_name != NULL) {
  20. if (flags & NI_NOFQDN) {
  21. if ( (ptr = strchr(hptr->h_name, '.')) != NULL)
  22. *ptr = 0; /* overwrite first dot */
  23. }
  24. snprintf(host, hostlen, "%s", hptr->h_name);
  25. } else {
  26. if (flags & NI_NAMEREQD)
  27. return(1);
  28. if (inet_ntop(family, aptr, host, hostlen) == NULL)
  29. return(1);
  30. }
  31. }
  32. }
  33. if (servlen > 0) {
  34. if (flags & NI_NUMERICSERV) {
  35. snprintf(serv, servlen, "%d", ntohs(port));
  36. } else {
  37. sptr = getservbyport(port, (flags & NI_DGRAM) ? "udp" : NULL);
  38. if (sptr != NULL && sptr->s_name != NULL)
  39. snprintf(serv, servlen, "%s", sptr->s_name);
  40. else
  41. snprintf(serv, servlen, "%d", ntohs(port));
  42. }
  43. }
  44. return(0);
  45. }
  46. /* end gn_ipv46 */