socket.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. #include "../kselftest.h"
  10. struct socket_testcase {
  11. int domain;
  12. int type;
  13. int protocol;
  14. /* 0 = valid file descriptor
  15. * -foo = error foo
  16. */
  17. int expect;
  18. /* If non-zero, accept EAFNOSUPPORT to handle the case
  19. * of the protocol not being configured into the kernel.
  20. */
  21. int nosupport_ok;
  22. };
  23. static struct socket_testcase tests[] = {
  24. { AF_MAX, 0, 0, -EAFNOSUPPORT, 0 },
  25. { AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, 1 },
  26. { AF_INET, SOCK_DGRAM, IPPROTO_TCP, -EPROTONOSUPPORT, 1 },
  27. { AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0, 1 },
  28. { AF_INET, SOCK_STREAM, IPPROTO_UDP, -EPROTONOSUPPORT, 1 },
  29. };
  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. }