Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <winsock.h>
- #include <iostream>
- #include <string>
- #include <cstdlib>
- using namespace std;
- void UDPClient(char * hostaddress, short nPort);
- int main()
- {
- WORD wVersionRequested = MAKEWORD(2,2);
- WSADATA wsadata;
- int nRet;
- short nPort;
- char host_address[256];
- cout << "Klient UDP" << endl;
- cout << "Podaj adres hosta: ";
- cin.getline(host_address, 256, '\n');
- cout << "Podaj nr portu: ";
- cin >> nPort;
- nRet = WSAStartup(wVersionRequested, &wsadata);
- if(wsadata.wVersion != wVersionRequested)
- {
- cout << "WSADATA error: " << WSAGetLastError() << endl;
- return -1;
- }
- UDPClient(host_address, nPort);
- WSACleanup();
- cin.get();
- return 0;
- }
- void UDPClient(char * hostaddress, short nPort)
- {
- cout << "Klient UDP" << endl;
- LPHOSTENT lpHostEntry;
- lpHostEntry = gethostbyname(hostaddress);
- if(lpHostEntry == NULL)
- {
- cout << "gethostbyname() error: " << WSAGetLastError() << endl;
- return;
- }
- cout << "Nawiazywanie polaczenia z serwerem: " << hostaddress << " na porcie: " << nPort << endl;
- SOCKET clientsocket;
- clientsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- if(clientsocket == INVALID_SOCKET)
- {
- cout << "SOCKET error: " << WSAGetLastError() << endl;
- return;
- }
- SOCKADDR_IN serveraddr;
- serveraddr.sin_family = AF_INET;
- serveraddr.sin_addr = *((LPIN_ADDR)*(lpHostEntry->h_addr_list));
- serveraddr.sin_port = htons(nPort);
- char Buffer[256];
- cout << "Wpisz komunikat: ";
- cin >> Buffer;
- int nRet;
- int nLength = sizeof(serveraddr);
- nRet = sendto(clientsocket, Buffer, strlen(Buffer), 0, (LPSOCKADDR)&serveraddr, nLength);
- if(nRet == SOCKET_ERROR)
- {
- cout << "sendto() error: " << WSAGetLastError() << endl;
- closesocket(clientsocket);
- return;
- }
- memset(Buffer, 0, sizeof(Buffer));
- nRet = recvfrom(clientsocket, Buffer, sizeof(Buffer), 0, (LPSOCKADDR)&serveraddr, &nLength);
- if(nRet == SOCKET_ERROR)
- {
- cout << "recvfrom() error: " << WSAGetLastError << endl;
- closesocket(clientsocket);
- return;
- }
- cout << "Komunikat zwrotny: " << Buffer << endl;
- closesocket(clientsocket);
- cin.get();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement