tcp.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "stdio.h"
  2. #include "string.h"
  3. #if defined(_WIN32)
  4. #else
  5. # include <errno.h>
  6. #endif
  7. #include "tcp.h"
  8. #include "../../common/MiscFunctions.h"
  9. #if defined(_WIN32)
  10. static int initialized = 0;
  11. #endif
  12. bool TCP::Start() {
  13. #if defined(_WIN32)
  14. WSAData wsa;
  15. //each program only needs to do this once. so if mulitple TCP servers or
  16. //clients are being used, we only need to initialize WinSock once
  17. if (initialized == 0) {
  18. if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
  19. return false;
  20. }
  21. ++initialized;
  22. #endif
  23. return true;
  24. }
  25. void TCP::Stop() {
  26. #if defined(_WIN32)
  27. if (initialized > 0) {
  28. if (--initialized == 0)
  29. WSACleanup();
  30. }
  31. #endif
  32. }
  33. void TCP::StoreError(char *dst, unsigned int size) {
  34. #if defined(_WIN32)
  35. char *ptr;
  36. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&ptr, 0, NULL);
  37. strlcpy(dst, ptr, size);
  38. LocalFree(ptr);
  39. ptr = strchr(dst, '\n');
  40. if (ptr != NULL)
  41. *ptr = '\0';
  42. #else
  43. strlcpy(dst, strerror(errno), size);
  44. #endif
  45. }
  46. bool TCP::GetIPAddressString(struct sockaddr_storage *addr, char *host, unsigned int host_size, char *port, unsigned int port_size) {
  47. switch (addr->ss_family) {
  48. case AF_INET:
  49. inet_ntop(AF_INET, &(((struct sockaddr_in *)addr)->sin_addr), host, host_size);
  50. if (port != NULL)
  51. snprintf(port, port_size, "%u", ((struct sockaddr_in *)addr)->sin_port);
  52. break;
  53. case AF_INET6:
  54. inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)addr)->sin6_addr), host, host_size);
  55. if (port != NULL)
  56. snprintf(port, port_size, "%u", ((struct sockaddr_in6 *)addr)->sin6_port);
  57. break;
  58. default:
  59. host[0] = '\0';
  60. if (port != NULL)
  61. port[0] = '\0';
  62. break;
  63. }
  64. return host[0] != '\0' && (port == NULL || port[0] != '\0');
  65. }