pair.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include "pair.h"
  2. int SocketPair(SOCKET socks[2], bool overlapped, bool cloexec) {
  3. #if defined(_win_)
  4. struct sockaddr_in addr;
  5. SOCKET listener;
  6. int e;
  7. int addrlen = sizeof(addr);
  8. DWORD flags = (overlapped ? WSA_FLAG_OVERLAPPED : 0) | (cloexec ? WSA_FLAG_NO_HANDLE_INHERIT : 0);
  9. if (socks == 0) {
  10. WSASetLastError(WSAEINVAL);
  11. return SOCKET_ERROR;
  12. }
  13. socks[0] = INVALID_SOCKET;
  14. socks[1] = INVALID_SOCKET;
  15. if ((listener = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
  16. return SOCKET_ERROR;
  17. }
  18. memset(&addr, 0, sizeof(addr));
  19. addr.sin_family = AF_INET;
  20. addr.sin_addr.s_addr = htonl(0x7f000001);
  21. addr.sin_port = 0;
  22. e = bind(listener, (const struct sockaddr*)&addr, sizeof(addr));
  23. if (e == SOCKET_ERROR) {
  24. e = WSAGetLastError();
  25. closesocket(listener);
  26. WSASetLastError(e);
  27. return SOCKET_ERROR;
  28. }
  29. e = getsockname(listener, (struct sockaddr*)&addr, &addrlen);
  30. if (e == SOCKET_ERROR) {
  31. e = WSAGetLastError();
  32. closesocket(listener);
  33. WSASetLastError(e);
  34. return SOCKET_ERROR;
  35. }
  36. do {
  37. if (listen(listener, 1) == SOCKET_ERROR)
  38. break;
  39. if ((socks[0] = WSASocket(AF_INET, SOCK_STREAM, 0, nullptr, 0, flags)) == INVALID_SOCKET)
  40. break;
  41. if (connect(socks[0], (const struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR)
  42. break;
  43. if ((socks[1] = accept(listener, nullptr, nullptr)) == INVALID_SOCKET)
  44. break;
  45. closesocket(listener);
  46. return 0;
  47. } while (0);
  48. e = WSAGetLastError();
  49. closesocket(listener);
  50. closesocket(socks[0]);
  51. closesocket(socks[1]);
  52. WSASetLastError(e);
  53. return SOCKET_ERROR;
  54. #else
  55. (void)overlapped;
  56. #if defined(_linux_)
  57. return socketpair(AF_LOCAL, SOCK_STREAM | (cloexec ? SOCK_CLOEXEC : 0), 0, socks);
  58. #else
  59. int r = socketpair(AF_LOCAL, SOCK_STREAM, 0, socks);
  60. // Non-atomic wrt exec
  61. if (r == 0 && cloexec) {
  62. for (int i = 0; i < 2; ++i) {
  63. int flags = fcntl(socks[i], F_GETFD, 0);
  64. if (flags < 0) {
  65. return flags;
  66. }
  67. r = fcntl(socks[i], F_SETFD, flags | FD_CLOEXEC);
  68. if (r < 0) {
  69. return r;
  70. }
  71. }
  72. }
  73. return r;
  74. #endif
  75. #endif
  76. }