You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.9 KiB

  1. #include "win32.h"
  2. #ifdef setsockopt
  3. #undef setsockopt
  4. #endif
  5. void winsock_init(void)
  6. {
  7. WORD wVersionRequested;
  8. WSADATA wsaData;
  9. int ret;
  10. wVersionRequested = MAKEWORD(1, 1);
  11. ret = WSAStartup(wVersionRequested, &wsaData);
  12. if (ret != 0) {
  13. FATAL("Could not initialize winsock");
  14. }
  15. if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) {
  16. WSACleanup();
  17. FATAL("Could not find a usable version of winsock");
  18. }
  19. }
  20. void winsock_cleanup(void)
  21. {
  22. WSACleanup();
  23. }
  24. void ss_error(const char *s)
  25. {
  26. LPVOID *msg = NULL;
  27. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  28. NULL, WSAGetLastError(),
  29. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  30. (LPTSTR) &msg, 0, NULL);
  31. if (msg != NULL) {
  32. LOGE("%s: %s", s, msg);
  33. LocalFree(msg);
  34. }
  35. }
  36. int setnonblocking(int fd)
  37. {
  38. u_long iMode = 0;
  39. int iResult;
  40. iResult = ioctlsocket(fd, FIONBIO, &iMode);
  41. if (iResult != NO_ERROR) {
  42. LOGE("ioctlsocket failed with error: %ld\n", iResult);
  43. }
  44. return iResult;
  45. }
  46. size_t strnlen(const char *s, size_t maxlen)
  47. {
  48. const char *end = memchr(s, 0, maxlen);
  49. return end ? (size_t) (end - s) : maxlen;
  50. }
  51. const char *inet_ntop(int af, const void *src, char *dst, socklen_t size)
  52. {
  53. struct sockaddr_storage ss;
  54. unsigned long s = size;
  55. ZeroMemory(&ss, sizeof(ss));
  56. ss.ss_family = af;
  57. switch (af) {
  58. case AF_INET:
  59. ((struct sockaddr_in *)&ss)->sin_addr = *(struct in_addr *)src;
  60. break;
  61. case AF_INET6:
  62. ((struct sockaddr_in6 *)&ss)->sin6_addr = *(struct in6_addr *)src;
  63. break;
  64. default:
  65. return NULL;
  66. }
  67. return (WSAAddressToString((struct sockaddr *)&ss, sizeof(ss), NULL, dst, &s) == 0) ? dst : NULL;
  68. }