Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. // UDPClient.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <WS2tcpip.h>
  6. #include <iostream>
  7. #include <conio.h>
  8. #include <string>
  9. using namespace std;
  10.  
  11. #pragma comment(lib,"ws2_32.lib")
  12.  
  13. int _tmain(int argc, char* argv[])
  14. {
  15. WSADATA wsaData;
  16. WORD version = MAKEWORD(2,2);
  17.  
  18. struct sockaddr_in remaddr; /* remote address */
  19. socklen_t addrlen = sizeof(remaddr);
  20.  
  21.  
  22. int wsOk = WSAStartup(version, &wsaData);
  23. if(wsOk != 0)
  24. {
  25. cout<<"Error Winsok sie nie uruchomil";
  26. return 0;
  27. }
  28.  
  29. // Create a hint structure for the server
  30. sockaddr_in server;
  31. server.sin_family = AF_INET; // AF_INET = IPv4 addresses
  32. server.sin_port = htons(54000); // Little to big endian conversion
  33. inet_pton(AF_INET, "192.168.1.10", &server.sin_addr); // Convert from string to byte array
  34.  
  35. // Socket creation, note that the socket type is datagram
  36. SOCKET out = socket(AF_INET, SOCK_DGRAM, 0);
  37.  
  38. // Write out to that socket
  39. string s = "Dupa";
  40. int sendOk = sendto(out, s.c_str(), s.size() + 1, 0, (sockaddr*)&server, sizeof(server));
  41.  
  42. if (sendOk == SOCKET_ERROR)
  43. {
  44. cout << "That didn't work! " << WSAGetLastError() << endl;
  45. }
  46. char *buf;
  47.  
  48. for (;;) {
  49.  
  50. int recvlen = recvfrom(out, buf, sizeof(buf), 0, (struct sockaddr *)&remaddr, &addrlen);
  51. printf("received %d bytes\n", recvlen);
  52. if (recvlen > 0) {
  53. buf[recvlen] = 0;
  54. printf("received message: \"%s\"\n", buf);
  55. }
  56. }
  57. // Close the socket
  58. closesocket(out);
  59.  
  60. // Close down Winsock
  61. WSACleanup();
  62. _getch();
  63. return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement