Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Klient.cpp : Defines the entry point for the console application.
- // 2018-04-13-udp-broadcast-kilent.cpp : Defines the entry point for the console application.
- #include "stdafx.h"
- #include <winsock.h>
- #include <conio.h>
- #include <locale.h>
- #pragma comment(lib, "ws2_32")
- int main() {
- setlocale(LC_ALL, "Polish");
- WSAData ws;
- if (WSAStartup(MAKEWORD(1, 0), &ws) != 0)
- {
- printf("Błąd inicjalizacji biblioteki WinSock.\n");
- _getch();
- return 0;
- }
- printf("Biblioteka WinSock utworzona pomyslnie.\n");
- SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- if (sock == INVALID_SOCKET)
- {
- printf("Błąd utworzenia gniazda.\n");
- _getch();
- WSACleanup();
- return 0;
- }
- printf("Gniazdo utworzone pomyślnie.\n");
- sockaddr_in broadcast;
- broadcast.sin_addr.s_addr = INADDR_BROADCAST;
- broadcast.sin_port = htons(7602);
- broadcast.sin_family = AF_INET;
- int one = 1;
- setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char*)&one, sizeof(one));
- sockaddr_in address;
- int addrSize = sizeof(address);
- sockaddr_in serverUnicast;
- serverUnicast.sin_addr.s_addr = inet_addr("192.168.0.13");
- serverUnicast.sin_port = htons(7602);
- serverUnicast.sin_family = AF_INET;
- timeval time = { 0, 100000 };
- fd_set set;
- char recBuff[128];
- memset(recBuff, 0, sizeof(recBuff));
- char buff[128];
- memset(buff, 0, sizeof(buff));
- buff[0] = 0x30;
- buff[1] = 0x1D;
- strcat(buff, "Ulubiony język programowania?");
- buff[31] = 0x4;
- strcat(buff, "Java");
- buff[36] = 0x3;
- strcat(buff, "C++");
- buff[40] = 0x6;
- strcat(buff, "Python");
- buff[47] = 0x2;
- strcat(buff, "C#");
- sendto(sock, buff, sizeof(buff), 0, (SOCKADDR*)&broadcast, sizeof(broadcast));
- while (true)
- {
- FD_ZERO(&set);
- FD_SET(sock, &set);
- if (select(0, &set, 0, 0, &time) > 0)
- {
- if (FD_ISSET(sock, &set))
- {
- recvfrom(sock, recBuff, sizeof(recBuff), 0, (SOCKADDR*)&address, &addrSize);
- }
- }
- if (_kbhit())
- {
- char c = _getch();
- if (c == 27)
- break;
- if (c == 32)
- {
- memset(buff, 0, sizeof(buff));
- buff[0] = 0x30;
- buff[1] = 0x1D;
- strcat(buff, "Ulubiony język programowania?");
- buff[31] = 0x4;
- strcat(buff, "Java");
- buff[36] = 0x3;
- strcat(buff, "C++");
- buff[40] = 0x6;
- strcat(buff, "Python");
- buff[47] = 0x2;
- strcat(buff, "C#");
- sendto(sock, buff, sizeof(buff), 0, (SOCKADDR*)&broadcast, sizeof(broadcast));
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement