Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // lab4.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <conio.h>
- #include <WinSock2.h>
- #pragma comment(lib, "Ws2_32.lib")
- int _tmain(int argc, _TCHAR* argv[])
- {
- WSADATA ws;
- SOCKET sock;
- int retcode=0;
- if(WSAStartup(MAKEWORD(2, 2), &ws)==NO_ERROR)
- {
- unsigned int res;
- sock=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- if(sock==INVALID_SOCKET)
- {
- printf("Failed to open socket\n");
- retcode=2;
- }else{
- sockaddr_in address;
- address.sin_family=AF_INET;
- address.sin_addr.s_addr=INADDR_ANY;
- address.sin_port=htons(2000);
- if(bind(sock,(SOCKADDR*) &address,sizeof(address))==SOCKET_ERROR)
- {
- printf("bind failed with error id %d\n",WSAGetLastError());
- retcode=3;
- }else{
- address.sin_port=htons(3000);
- address.sin_addr.s_addr=inet_addr("192.168.0.67");
- const char sendarray[4]={50,100,150};
- do
- {
- printf("Init sequence sent\n");
- res=sendto(sock,sendarray,3,0,(SOCKADDR*)&address,sizeof(address));
- if(res==SOCKET_ERROR)
- {
- printf("sendto failed with error id %d\n",WSAGetLastError());
- }else{
- sockaddr_in Sender;
- int addrsize=sizeof(Sender);
- unsigned short bufor[100];
- res=recvfrom(sock,(char*) bufor , sizeof(bufor),0,(SOCKADDR*) &Sender,&addrsize);
- if(res==SOCKET_ERROR)
- {
- printf("recvfrom failed with error id %d\n",WSAGetLastError());
- }else{
- unsigned short suma=0;
- for(unsigned int i=0;i<res;i++)
- {
- printf("Received number %d = %d\n",i+1,bufor[i]);
- suma+=bufor[i];
- }
- printf("Calculated number %d\n",suma);
- res=sendto(sock,(char*) &suma,sizeof(unsigned short),0,(SOCKADDR*) &address,sizeof(address));
- if(res==SOCKET_ERROR)
- {
- printf("sendto(1) failed with error id %d\n",WSAGetLastError());
- }else{
- printf("Number successfully sent\n");
- }
- }
- }
- printf("Press any key to send, ESC to exit\n");
- }while(_getch()!=27);
- }
- res=closesocket(sock);
- if(res==SOCKET_ERROR)
- {
- printf("closesocket failed with error id %d",WSAGetLastError());
- retcode=5;
- }
- }
- res=WSACleanup();
- if(res==SOCKET_ERROR)
- {
- printf("WSACleanup failed with error id %d",WSAGetLastError());
- retcode=6;
- }
- }else{
- printf("Failed to initialize Winsock\n");
- retcode=1;
- }
- _getch();
- return retcode;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement