opensock.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* Copyright (C) 1999-2019 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, see
  13. <http://www.gnu.org/licenses/>. */
  14. #include <stdio.h>
  15. #include <sys/socket.h>
  16. #include <libc-lock.h>
  17. /* Return a socket of any type. The socket can be used in subsequent
  18. ioctl calls to talk to the kernel. */
  19. int
  20. __opensock (void)
  21. {
  22. /* Cache the last AF that worked, to avoid many redundant calls to
  23. socket(). */
  24. static int sock_af = -1;
  25. int fd = -1;
  26. __libc_lock_define_initialized (static, lock);
  27. if (sock_af != -1)
  28. {
  29. fd = __socket (sock_af, SOCK_DGRAM, 0);
  30. if (fd != -1)
  31. return fd;
  32. }
  33. __libc_lock_lock (lock);
  34. if (sock_af != -1)
  35. fd = __socket (sock_af, SOCK_DGRAM, 0);
  36. if (fd == -1)
  37. {
  38. #ifdef AF_INET
  39. fd = __socket (sock_af = AF_INET, SOCK_DGRAM, 0);
  40. #endif
  41. #ifdef AF_INET6
  42. if (fd < 0)
  43. fd = __socket (sock_af = AF_INET6, SOCK_DGRAM, 0);
  44. #endif
  45. #ifdef AF_IPX
  46. if (fd < 0)
  47. fd = __socket (sock_af = AF_IPX, SOCK_DGRAM, 0);
  48. #endif
  49. #ifdef AF_AX25
  50. if (fd < 0)
  51. fd = __socket (sock_af = AF_AX25, SOCK_DGRAM, 0);
  52. #endif
  53. #ifdef AF_APPLETALK
  54. if (fd < 0)
  55. fd = __socket (sock_af = AF_APPLETALK, SOCK_DGRAM, 0);
  56. #endif
  57. }
  58. __libc_lock_unlock (lock);
  59. return fd;
  60. }