Advertisement
Guest User

Untitled

a guest
Jan 24th, 2020
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. /*
  2. TCP Server
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7.  
  8. #ifdef __linux__
  9. // gcc tcp_main.c -w -o tcp_main && ./tcp_main
  10. #include <sys/socket.h>
  11. #include <netinet/in.h>
  12. #include <netinet/ip.h>
  13. #include <unistd.h>
  14. #elif _WIN32
  15. // compile with linker settings: "gcc tcp_main.c -lws2_32"
  16. g++ main.cpp - lws2_32
  17. #define _WIN32_WINNT 0x0A00
  18. #include <winsock2.h>
  19. #include <ws2tcpip.h>
  20. #endif
  21.  
  22. int main()
  23. {
  24. #ifdef _WIN32 // Win Only: Treiber Starten
  25. WSADATA wsaData;
  26. int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  27. if (iResult != 0)
  28. {
  29. printf("WSAStartup failed: %d\n", iResult);
  30. return 1;
  31. }
  32. #endif
  33.  
  34. // socket()
  35. int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  36. printf("socket: %i\n", s);
  37.  
  38. // bind()
  39. struct sockaddr_in srvAddr;
  40. srvAddr.sin_family = AF_INET;
  41. srvAddr.sin_port = htons(3334); // port
  42. srvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  43.  
  44. int b = bind(s, &srvAddr, sizeof(srvAddr));
  45. printf("bind: %i\n", b);
  46.  
  47. // listen()
  48. int queue = SOMAXCONN; // handle this amount of clients
  49. printf("listen: %i\n", listen(s, queue));
  50.  
  51. // accept()
  52. struct sockaddr_in cliAddr;
  53. int size = sizeof(cliAddr);
  54. int cliSocket = accept(s, (struct socketaddr *)&cliAddr, &size);
  55. printf("listen sock: %i\n", cliSocket);
  56.  
  57. char str[128];
  58. int r = recv(cliSocket, str, 100, 0);
  59. printf("receive: %i\n", r);
  60. printf("data: %s\n", str);
  61.  
  62. #ifdef __linux__
  63. close(s);
  64. #elif _WIN32 // Win Only: Treiber Beenden
  65. closesocket(s);
  66. int iReuslt = WSACleanup();
  67. #endif
  68. return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement