Advertisement
Ghostriax-Atrocity

AbstractSocket.cpp

Apr 11th, 2015
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include "abstractsocket.h"
  3.  
  4.  
  5. AbstractSocket::AbstractSocket()
  6. {
  7. timeoutvalsec = 2;
  8.  
  9. if(INVALID_SOCKET == (s = socket(AF_INET, SOCK_STREAM, 0)))
  10. {
  11. throw "with poop"; // Hihi
  12. }
  13. }
  14.  
  15. VOID AbstractSocket::Disconnect()
  16. {
  17. closesocket(s);
  18. s = INVALID_SOCKET;
  19. }
  20.  
  21. __forceinline bool HasConnectedSuccessful(SOCKET s)
  22. {
  23. SOCKADDR out = {0};
  24. int outlen = sizeof(SOCKADDR);
  25. const unsigned char nulledIP[14]= {0};
  26.  
  27. getpeername(s, &out, &outlen);
  28.  
  29. return 0 != memcmp(out.sa_data, nulledIP, sizeof(nulledIP));
  30. }
  31.  
  32. BOOL AbstractSocket::ConnectWithTimeout()
  33. {
  34. fd_set write, err;
  35. struct timeval timeout;
  36. int status;
  37.  
  38. unsigned long opt = 1;
  39. ioctlsocket(s, FIONBIO, &opt);
  40.  
  41. if (SOCKET_ERROR == (status = connect(s, (struct sockaddr*) &addr, sizeof(addr))))
  42. {
  43. if(WSAEWOULDBLOCK != WSAGetLastError())
  44. {
  45. return FALSE;
  46. }
  47. }
  48.  
  49. // Already finished
  50. if(0 == status)
  51. return TRUE;
  52.  
  53. FD_ZERO(&write);
  54. FD_ZERO(&err);
  55. FD_SET(s, &write);
  56. FD_SET(s, &err);
  57.  
  58. timeout.tv_sec = timeoutvalsec;
  59. timeout.tv_usec = 0;
  60.  
  61. if (SOCKET_ERROR == select(0, 0, &write, &err, &timeout) || FD_ISSET(s, &err))
  62. {
  63. return FALSE;
  64. }
  65.  
  66. opt = 0;
  67. ioctlsocket(s, FIONBIO, &opt);
  68.  
  69. if (0 == FD_ISSET(s, &write))
  70. {
  71. return FALSE;
  72. }
  73.  
  74. return HasConnectedSuccessful(s);
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement