Advertisement
Guest User

Untitled

a guest
May 22nd, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. #include <sys/socket.h>
  2. #include <sys/un.h>
  3. #include <netinet/in.h>
  4. #include <netdb.h>
  5.  
  6. #include <assert.h>
  7.  
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <stddef.h>
  11. #include <unistd.h>
  12. #include <string.h>
  13.  
  14. void nameinfo(struct sockaddr *sa, socklen_t salen, char *prefix)
  15. {
  16. char ntop[NI_MAXHOST];
  17. char strport[NI_MAXSERV];
  18.  
  19. if (sa->sa_family == AF_UNIX) {
  20. struct sockaddr_un *sun = (struct sockaddr_un *)sa;
  21. socklen_t len = offsetof(struct sockaddr_un, sun_path);
  22. assert(salen >= len);
  23. // XXX: salen take '\0' into account
  24. sun->sun_path[salen - len] = '\0';
  25. }
  26.  
  27. assert(!getnameinfo(sa, salen,
  28. ntop, sizeof(ntop),
  29. strport, sizeof(strport),
  30. NI_NUMERICHOST|NI_NUMERICSERV));
  31.  
  32. printf("%ssocklen=%i, family=%i, host=%s, serv=%s\n",
  33. prefix, salen, sa->sa_family, ntop, strport);
  34. }
  35.  
  36. int main()
  37. {
  38. int fd;
  39. struct sockaddr_storage ss;
  40. struct sockaddr *sa = (struct sockaddr *)&ss;
  41. struct sockaddr_un *sun = (struct sockaddr_un *)&ss;
  42. socklen_t salen;
  43.  
  44. puts("AF_UNIX:");
  45. fd = socket(AF_UNIX, SOCK_STREAM, 0);
  46. salen = sizeof(ss);
  47. assert(!getsockname(fd, sa, &salen));
  48. nameinfo(sa, salen, " ");
  49.  
  50. puts(" bind():");
  51. memset(&ss, 0, sizeof(ss));
  52. sun->sun_family = AF_UNIX;
  53. strcpy(sun->sun_path, "/tmp/sock");
  54. unlink(sun->sun_path);
  55. salen = sizeof(*sun);
  56. assert(!bind(fd, sa, salen));
  57. assert(!getsockname(fd, sa, &salen));
  58. nameinfo(sa, salen, " ");
  59.  
  60. return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement