socket.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. const char *msg1, *msg2;
  36. int i, err;
  37. err = 0;
  38. for (i = 0; i < ARRAY_SIZE(tests); i++) {
  39. struct socket_testcase *s = &tests[i];
  40. int fd;
  41. fd = socket(s->domain, s->type, s->protocol);
  42. if (fd < 0) {
  43. if (s->nosupport_ok &&
  44. errno == EAFNOSUPPORT)
  45. continue;
  46. if (s->expect < 0 &&
  47. errno == -s->expect)
  48. continue;
  49. msg1 = strerror_r(-s->expect, err_string1, ERR_STRING_SZ);
  50. msg2 = strerror_r(errno, err_string2, ERR_STRING_SZ);
  51. fprintf(stderr, "socket(%d, %d, %d) expected "
  52. "err (%s) got (%s)\n",
  53. s->domain, s->type, s->protocol,
  54. msg1, msg2);
  55. err = -1;
  56. break;
  57. } else {
  58. close(fd);
  59. if (s->expect < 0) {
  60. msg1 = strerror_r(errno, err_string1, ERR_STRING_SZ);
  61. fprintf(stderr, "socket(%d, %d, %d) expected "
  62. "success got err (%s)\n",
  63. s->domain, s->type, s->protocol,
  64. msg1);
  65. err = -1;
  66. break;
  67. }
  68. }
  69. }
  70. return err;
  71. }
  72. int main(void)
  73. {
  74. int err = run_tests();
  75. return err;
  76. }