Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <stdio.h>
- #include <winsock.h>
- #include <conio.h>
- #pragma comment(lib,"ws2_32.lib") //Winsock Library
- #define SERVER "192.168.0.13" //ip address of udp server
- #define BUFLEN 512 //Max length of buffer
- #define PORT 7505 //The port on which to listen for incoming data
- struct temperature
- {
- short year;
- char month;
- char day;
- double value;
- };
- struct pressure
- {
- short year;
- char month;
- char day;
- float value;
- };
- int main(void)
- {
- struct temperature* T;
- struct pressure* P;
- int n;
- struct sockaddr_in si_other;
- int s, slen = sizeof(si_other);
- char buf[BUFLEN];
- char message[BUFLEN];
- WSADATA wsa;
- //Initialise winsock
- printf("\nInitialising Winsock...");
- if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
- {
- printf("Failed. Error Code : %d", WSAGetLastError());
- exit(EXIT_FAILURE);
- }
- printf("Initialised.\n");
- //create socket
- if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
- {
- printf("socket() failed with error code : %d", WSAGetLastError());
- exit(EXIT_FAILURE);
- }
- //setup address structure
- memset((char *)&si_other, 0, sizeof(si_other));
- si_other.sin_family = AF_INET;
- si_other.sin_port = htons(PORT);
- si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);
- //start communication
- while (1)
- {
- printf("Enter message : ");
- scanf("%s",message);
- if (strcmp(message, "exit") == 0)
- break;
- //send the message
- if (sendto(s, message, strlen(message), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
- {
- printf("sendto() failed with error code : %d", WSAGetLastError());
- getch();
- exit(EXIT_FAILURE);
- }
- //receive a reply and print it
- //clear the buffer by filling null, it might have previously received data
- memset(buf, '\0', BUFLEN);
- //try to receive some data, this is a blocking call
- if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == SOCKET_ERROR)
- {
- printf("recvfrom() failed with error code : %d", WSAGetLastError());
- getch();
- exit(EXIT_FAILURE);
- }
- if ((short)buf[0] == -1)
- {
- printf("Nieprawidlowe polecenie");
- }
- if (buf[0] == 0x17)
- {
- n = (int)buf[1];
- printf("Temperatura\n");
- for (int i = 0; i < n; i++)
- {
- T = (temperature*)buf[5 + i * sizeof(temperature)];
- printf("%d-%d-%d\t%lf\n", T->year, T->month, T->day, T->value);
- }
- }
- if (buf[0] == 0x18)
- {
- n = (int)buf[1];
- printf("Cisnienie");
- for (int i = 0; i < n; i++)
- {
- P = (pressure*)buf[5 + i * sizeof(pressure)];
- printf("%d-%d-%d\t%f\n", P->year, P->month, P->day, P->value);
- }
- }
- }
- closesocket(s);
- WSACleanup();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement