Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // WinSock32Test.cpp : Defines the entry point for the console application.
- //
- #define WIN32_LEAN_AND_MEAN
- #include <Windows.h>
- #include <WinSock2.h>
- #include <ws2tcpip.h>
- #include <iphlpapi.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <tchar.h>
- #pragma comment(lib, "Ws2_32.lib")
- #define DEFAULT_PORT "27015"
- #define BUFSIZE 1024
- int _tmain(int argc, _TCHAR* argv[])
- {
- WSADATA wsaData;
- int iResult;
- TCHAR buf[BUFSIZE];
- sockaddr_in remaddr;
- socklen_t addrlen = sizeof(remaddr);
- int recvlen;
- iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
- if (iResult != 0){
- printf("WSAStartup failed: %d\n", iResult);
- return 1;
- }
- struct addrinfo *result = NULL, *ptr = NULL, hints;
- ZeroMemory(&hints, sizeof(hints));
- hints.ai_family = AF_INET;
- hints.ai_socktype = SOCK_DGRAM;
- hints.ai_protocol = IPPROTO_UDP;
- hints.ai_flags = AI_PASSIVE;
- iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
- if (iResult != 0) {
- printf("getaddrinfo failed: %d\n", iResult);
- WSACleanup();
- return 1;
- }
- SOCKET ListenSocket = INVALID_SOCKET;
- ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
- if (ListenSocket == INVALID_SOCKET)
- {
- printf("Error at socket(): %ld\n", WSAGetLastError());
- freeaddrinfo(result);
- WSACleanup();
- return 1;
- }
- iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
- if (iResult == SOCKET_ERROR) {
- printf("bind failed with error: %d\n", WSAGetLastError());
- freeaddrinfo(result);
- closesocket(ListenSocket);
- WSACleanup();
- return 1;
- }
- freeaddrinfo(result);
- while (strncmp(buf, "END", BUFSIZE) != 0)
- {
- recvlen = recvfrom(ListenSocket, buf, BUFSIZE, 0, (sockaddr *)&remaddr, &addrlen);
- printf("received %d bytes\n", recvlen);
- if (recvlen > 0){
- buf[recvlen] = 0;
- printf("received message: %s\n", buf);
- }
- TCHAR sendBuf[] = "testReturn";
- int sendlen = sendto(ListenSocket, sendBuf, strlen(sendBuf), 0, (sockaddr *)&remaddr, addrlen);
- if (sendlen < 0)
- {
- printf("return message failed\n");
- }
- else
- {
- printf("return message sent\n");
- }
- }
- system("PAUSE");
- closesocket(ListenSocket);
- WSACleanup();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement