Advertisement
Guest User

Untitled

a guest
Jan 24th, 2020
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. /*
  2. UDP Server
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7.  
  8. #ifdef __linux__
  9. // gcc udp_main.c -w -o udp_main && ./udp_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 udp_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_DGRAM, IPPROTO_UDP);
  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(51234); // 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. struct sockaddr_in cliAddr;
  49. int size = sizeof(cliAddr);
  50. char str[128];
  51. int r = recvfrom(s, str, 100, 0, (struct sockaddr *)&cliAddr, &size);
  52. printf("receive: %i\n", r);
  53. printf("data: %s\n", str);
  54.  
  55. #ifdef __linux__
  56. close(s);
  57. #elif _WIN32 // Win Only: Treiber Beenden
  58. closesocket(s);
  59. int iReuslt = WSACleanup();
  60. #endif
  61. return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement