Advertisement
Alchemik96

PWSS [UDP] Broadcast 50,100,150

Apr 17th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. // lab4.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <conio.h>
  6. #include <WinSock2.h>
  7.  
  8. #pragma comment(lib, "Ws2_32.lib")
  9.  
  10.  
  11. int _tmain(int argc, _TCHAR* argv[])
  12. {
  13. WSADATA ws;
  14. SOCKET sock;
  15. int retcode=0;
  16. if(WSAStartup(MAKEWORD(2, 2), &ws)==NO_ERROR)
  17. {
  18. unsigned int res;
  19. sock=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  20. if(sock==INVALID_SOCKET)
  21. {
  22. printf("Failed to open socket\n");
  23. retcode=2;
  24. }else{
  25.  
  26. sockaddr_in address;
  27. address.sin_family=AF_INET;
  28. address.sin_addr.s_addr=INADDR_ANY;
  29. address.sin_port=htons(2000);
  30. if(bind(sock,(SOCKADDR*) &address,sizeof(address))==SOCKET_ERROR)
  31. {
  32. printf("bind failed with error id %d\n",WSAGetLastError());
  33. retcode=3;
  34. }else{
  35. address.sin_port=htons(3000);
  36. address.sin_addr.s_addr=inet_addr("192.168.0.67");
  37. const char sendarray[4]={50,100,150};
  38. do
  39. {
  40. printf("Init sequence sent\n");
  41. res=sendto(sock,sendarray,3,0,(SOCKADDR*)&address,sizeof(address));
  42. if(res==SOCKET_ERROR)
  43. {
  44. printf("sendto failed with error id %d\n",WSAGetLastError());
  45. }else{
  46. sockaddr_in Sender;
  47. int addrsize=sizeof(Sender);
  48. unsigned short bufor[100];
  49. res=recvfrom(sock,(char*) bufor , sizeof(bufor),0,(SOCKADDR*) &Sender,&addrsize);
  50. if(res==SOCKET_ERROR)
  51. {
  52. printf("recvfrom failed with error id %d\n",WSAGetLastError());
  53. }else{
  54. unsigned short suma=0;
  55. for(unsigned int i=0;i<res;i++)
  56. {
  57. printf("Received number %d = %d\n",i+1,bufor[i]);
  58. suma+=bufor[i];
  59. }
  60. printf("Calculated number %d\n",suma);
  61. res=sendto(sock,(char*) &suma,sizeof(unsigned short),0,(SOCKADDR*) &address,sizeof(address));
  62. if(res==SOCKET_ERROR)
  63. {
  64. printf("sendto(1) failed with error id %d\n",WSAGetLastError());
  65.  
  66. }else{
  67. printf("Number successfully sent\n");
  68. }
  69. }
  70. }
  71. printf("Press any key to send, ESC to exit\n");
  72. }while(_getch()!=27);
  73. }
  74. res=closesocket(sock);
  75. if(res==SOCKET_ERROR)
  76. {
  77. printf("closesocket failed with error id %d",WSAGetLastError());
  78. retcode=5;
  79. }
  80. }
  81. res=WSACleanup();
  82. if(res==SOCKET_ERROR)
  83. {
  84. printf("WSACleanup failed with error id %d",WSAGetLastError());
  85. retcode=6;
  86. }
  87. }else{
  88. printf("Failed to initialize Winsock\n");
  89. retcode=1;
  90. }
  91. _getch();
  92. return retcode;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement