sockets.c 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2016 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | This source file is subject to version 3.01 of the PHP license, |
  8. | that is bundled with this package in the file LICENSE, and is |
  9. | available through the world-wide-web at the following url: |
  10. | http://www.php.net/license/3_01.txt |
  11. | If you did not receive a copy of the PHP license and are unable to |
  12. | obtain it through the world-wide-web, please send a note to |
  13. | license@php.net so we can mail you a copy immediately. |
  14. +----------------------------------------------------------------------+
  15. | Authors: Chris Vandomelen <chrisv@b0rked.dhs.org> |
  16. | Sterling Hughes <sterling@php.net> |
  17. | |
  18. | WinSock: Daniel Beulshausen <daniel@php4win.de> |
  19. +----------------------------------------------------------------------+
  20. */
  21. /* $Id$ */
  22. /* Code originally from ext/sockets */
  23. #include <stdio.h>
  24. #include <fcntl.h>
  25. #include "php.h"
  26. PHPAPI int socketpair(int domain, int type, int protocol, SOCKET sock[2])
  27. {
  28. struct sockaddr_in address;
  29. SOCKET redirect;
  30. int size = sizeof(address);
  31. if(domain != AF_INET) {
  32. WSASetLastError(WSAENOPROTOOPT);
  33. return -1;
  34. }
  35. sock[0] = sock[1] = redirect = INVALID_SOCKET;
  36. sock[0] = socket(domain, type, protocol);
  37. if (INVALID_SOCKET == sock[0]) {
  38. goto error;
  39. }
  40. address.sin_addr.s_addr = INADDR_ANY;
  41. address.sin_family = AF_INET;
  42. address.sin_port = 0;
  43. if (bind(sock[0], (struct sockaddr*)&address, sizeof(address)) != 0) {
  44. goto error;
  45. }
  46. if(getsockname(sock[0], (struct sockaddr *)&address, &size) != 0) {
  47. goto error;
  48. }
  49. if (listen(sock[0], 2) != 0) {
  50. goto error;
  51. }
  52. sock[1] = socket(domain, type, protocol);
  53. if (INVALID_SOCKET == sock[1]) {
  54. goto error;
  55. }
  56. address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  57. if(connect(sock[1], (struct sockaddr*)&address, sizeof(address)) != 0) {
  58. goto error;
  59. }
  60. redirect = accept(sock[0],(struct sockaddr*)&address, &size);
  61. if (INVALID_SOCKET == redirect) {
  62. goto error;
  63. }
  64. closesocket(sock[0]);
  65. sock[0] = redirect;
  66. return 0;
  67. error:
  68. closesocket(redirect);
  69. closesocket(sock[0]);
  70. closesocket(sock[1]);
  71. WSASetLastError(WSAECONNABORTED);
  72. return -1;
  73. }