Advertisement
Cieslin

WinSock_UDP_S

Mar 12th, 2018
1,163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // WinSock()_S_Udp.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <winsock.h>
  7. #include <conio.h>
  8. struct Dane{
  9.     char name;
  10.     int liczba;
  11. };
  12. int main()
  13. {
  14.     WORD wersja= MAKEWORD(2, 2);
  15.     WSADATA wsData;
  16.     if (WSAStartup(wersja, &wsData) != 0)
  17.     {
  18.         printf("Blad inicjalizacji WinSock()!");
  19.         _getch();
  20.         return 0;
  21.     }
  22.     //////////////////////////
  23.     SOCKET gniazdo;
  24.     if ((gniazdo = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
  25.     {
  26.         printf("Blad ladowania gniazda: %d",INVALID_SOCKET);
  27.         shutdown(gniazdo, 2);
  28.         closesocket(gniazdo);
  29.         WSACleanup();
  30.         _getch();
  31.         return 0;
  32.     }
  33.     //////////////////////////
  34.     SOCKADDR_IN serwer;
  35.     serwer.sin_family = AF_INET;
  36.     serwer.sin_addr.s_addr = INADDR_ANY;
  37.     serwer.sin_port = htons(1234);
  38.     if ((bind(gniazdo, (SOCKADDR*)&serwer, sizeof(serwer))) == SOCKET_ERROR)
  39.     {
  40.         printf("Blad ladowania gniazda: %d", WSAGetLastError());
  41.         shutdown(gniazdo, 2);
  42.         closesocket(gniazdo);
  43.         WSACleanup();
  44.         _getch();
  45.         return 0;
  46.     }
  47.     Dane pakunek;
  48.     pakunek.name = 'd';
  49.     pakunek.liczba = 94;
  50.     char buff[8];
  51.     memset(buff, 0, sizeof(buff));
  52.     char odebrane[3];
  53.     SOCKADDR_IN klient;
  54.     int odebrany = sizeof(klient);
  55.     while(true)
  56.     {
  57.         if (recvfrom(gniazdo, odebrane, sizeof(odebrane), 0, (SOCKADDR*)&klient, &odebrany)==SOCKET_ERROR)
  58.         {
  59.             printf("Blad danych!");
  60.             break;
  61.         }
  62.         memset(odebrane, 0, sizeof(odebrane));
  63.         printf("Odebralem znaki %s\n", odebrane);
  64.         if (sendto(gniazdo, (char*)&pakunek, sizeof(pakunek), 0, (SOCKADDR*)&klient, sizeof(klient)) == INVALID_SOCKET)
  65.         {
  66.             printf("Odbieranie sie nie powiodlo");
  67.         }
  68.     }
  69.     //////////////////////////
  70.     _getch();
  71.     shutdown(gniazdo, 2);
  72.     closesocket(gniazdo);
  73.     WSACleanup();
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement