Advertisement
Cieslin

WinSock_SimpleUDP_K

Mar 18th, 2018
1,291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // WinSock_SimpleUDP.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <stdio.h>
  6. #include <winsock.h>
  7. #include <string.h>
  8. #include <conio.h>
  9. #include <locale.h>
  10. #pragma comment(lib,"WS2_32.lib")
  11.  
  12.  
  13.  
  14.  
  15. int main()
  16. {
  17.     int liczba = 0;
  18.     char liczbaSlowo[4];
  19.     char odebrane[32] = "Dzialam";
  20.     setlocale(LC_ALL, "Polish");
  21.     WSAData ws;
  22.     if (WSAStartup(MAKEWORD(2, 2), &ws) != 0)
  23.     {
  24.         printf("Blad ladowania biblioteki: %d", WSAGetLastError());
  25.         WSACleanup();
  26.         _getch();
  27.         return 0;
  28.     }
  29.     //////////////////////////////////////////////////////////////
  30.     SOCKET sock;
  31.     if (sock = socket(AF_INET, SOCK_DGRAM, 0) == SOCKET_ERROR)
  32.     {
  33.         printf("Blad ladowania gniazda: %d", WSAGetLastError());
  34.         shutdown(sock, 2);
  35.         closesocket(sock);
  36.         WSACleanup();
  37.         _getch();
  38.         return 0;
  39.     }
  40.  
  41.     SOCKADDR_IN klient;
  42.     klient.sin_family = AF_INET;
  43.     klient.sin_addr.s_addr = inet_addr("127.0.0.1"); //<- Adres servera
  44.     klient.sin_port = htons(1234); //<- PORT servera
  45.     while (true)
  46.     {
  47.         do {
  48.             printf("Podaj liczbe: ");
  49.             scanf("%d", &liczba);
  50.         } while (liczba > 1400);
  51.         if (liczba < 0)
  52.         {
  53.             shutdown(sock, 2);
  54.             closesocket(sock);
  55.             WSACleanup();
  56.             printf("Koniec działania programu! (Wpisano liczbę ujemną)");
  57.             _getch();
  58.             return 0;
  59.         }
  60.         _itoa(liczba, liczbaSlowo, 10);
  61.         sendto(sock, liczbaSlowo, sizeof(liczbaSlowo), 0, (SOCKADDR*)&klient, sizeof(klient));
  62.         SOCKADDR_IN serwerDanych;
  63.         int rozm = sizeof(serwerDanych);
  64.         recvfrom(sock, odebrane, sizeof(odebrane), 0, (SOCKADDR*)&serwerDanych, &rozm);
  65.         printf("Adres komputera: %s\nNumer portu źródłowego: %d\n[%s]\n\n\n", inet_ntoa(serwerDanych.sin_addr), ntohs(serwerDanych.sin_port), odebrane);
  66.     }
  67.     _getch();
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement