socket.c 1.9 KB

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