socket.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <stdio.h>
  2. #include <errno.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/socket.h>
  7. #include <netinet/in.h>
  8. struct socket_testcase {
  9. int domain;
  10. int type;
  11. int protocol;
  12. /* 0 = valid file descriptor
  13. * -foo = error foo
  14. */
  15. int expect;
  16. /* If non-zero, accept EAFNOSUPPORT to handle the case
  17. * of the protocol not being configured into the kernel.
  18. */
  19. int nosupport_ok;
  20. };
  21. static struct socket_testcase tests[] = {
  22. { AF_MAX, 0, 0, -EAFNOSUPPORT, 0 },
  23. { AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, 1 },
  24. { AF_INET, SOCK_DGRAM, IPPROTO_TCP, -EPROTONOSUPPORT, 1 },
  25. { AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0, 1 },
  26. { AF_INET, SOCK_STREAM, IPPROTO_UDP, -EPROTONOSUPPORT, 1 },
  27. };
  28. #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
  29. #define ERR_STRING_SZ 64
  30. static int run_tests(void)
  31. {
  32. char err_string1[ERR_STRING_SZ];
  33. char err_string2[ERR_STRING_SZ];
  34. int i, err;
  35. err = 0;
  36. for (i = 0; i < ARRAY_SIZE(tests); i++) {
  37. struct socket_testcase *s = &tests[i];
  38. int fd;
  39. fd = socket(s->domain, s->type, s->protocol);
  40. if (fd < 0) {
  41. if (s->nosupport_ok &&
  42. errno == EAFNOSUPPORT)
  43. continue;
  44. if (s->expect < 0 &&
  45. errno == -s->expect)
  46. continue;
  47. strerror_r(-s->expect, err_string1, ERR_STRING_SZ);
  48. strerror_r(errno, err_string2, ERR_STRING_SZ);
  49. fprintf(stderr, "socket(%d, %d, %d) expected "
  50. "err (%s) got (%s)\n",
  51. s->domain, s->type, s->protocol,
  52. err_string1, err_string2);
  53. err = -1;
  54. break;
  55. } else {
  56. close(fd);
  57. if (s->expect < 0) {
  58. strerror_r(errno, err_string1, ERR_STRING_SZ);
  59. fprintf(stderr, "socket(%d, %d, %d) expected "
  60. "success got err (%s)\n",
  61. s->domain, s->type, s->protocol,
  62. err_string1);
  63. err = -1;
  64. break;
  65. }
  66. }
  67. }
  68. return err;
  69. }
  70. int main(void)
  71. {
  72. int err = run_tests();
  73. return err;
  74. }