Advertisement
Guest User

Untitled

a guest
Jan 24th, 2020
101
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 Client
  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. // sendTo()
  39. char str[128] = "Hallo Server";
  40.  
  41. struct sockaddr_in srvAddr;
  42. srvAddr.sin_family = AF_INET;
  43. srvAddr.sin_port = htons(3333); // port
  44. srvAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  45. int size = sizeof(srvAddr);
  46.  
  47. int st = sendto(s, str, 100, 0, (struct sockaddr *)&srvAddr, size);
  48. printf("send: %i\n", st);
  49.  
  50. //int r = recvfrom(s, str, 100, 0, (struct sockaddr *)&srvAddr, &size);
  51. //printf("receive: %i\n", r);
  52. //printf("data: %s\n", str);
  53.  
  54. #ifdef __linux__
  55. close(s);
  56. #elif _WIN32 // Win Only: Treiber Beenden
  57. closesocket(s);
  58. int iReuslt = WSACleanup();
  59. #endif
  60. return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement