Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This should be placed before #include <Windows.h> if the windows include is used
- #ifndef WIN32_LEAN_AND_MEAN
- #define WIN32_LEAN_AND_MEAN
- #endif
- #include <cstdio>
- #include <Windows.h>
- #include <WinSock2.h>
- #include <WS2tcpip.h>
- /// TEST CODE /// REMOVE AFTER TESTING WAS DONE ///
- int main()
- {
- WSADATA wsaData;
- int iResult;
- 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_STREAM;
- hints.ai_protocol = IPPROTO_TCP;
- hints.ai_flags = AI_PASSIVE;
- // Resolve the local address and port to be used by the server
- iResult = getaddrinfo("109.xxx.xxx.xxx", "1337", &hints, &result);
- if (iResult != 0)
- {
- printf("getaddrinfo failed: %d\n", iResult);
- WSACleanup();
- return 1;
- }
- SOCKET ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (ConnectSocket == INVALID_SOCKET)
- {
- printf("Error at socket(): %ld\n", WSAGetLastError());
- freeaddrinfo(result);
- WSACleanup();
- }
- iResult = connect(ConnectSocket, result->ai_addr, (int)result->ai_addrlen);
- if (iResult == SOCKET_ERROR)
- {
- closesocket(ConnectSocket);
- ConnectSocket = INVALID_SOCKET;
- }
- // Should really try the next address returned by getaddrinfo
- // if the connect call failed
- // But for this simple example we just free the resources
- // returned by getaddrinfo and print an error message
- freeaddrinfo(result);
- if (ConnectSocket == INVALID_SOCKET)
- {
- printf("Unable to connect to server!\n");
- WSACleanup();
- return 1;
- }
- #define DEFAULT_BUFLEN 512
- int recvbuflen = DEFAULT_BUFLEN;
- const char* sendbuf = "this is a test";
- char recvbuf[DEFAULT_BUFLEN];
- // Send an initial buffer
- iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
- if (iResult == SOCKET_ERROR)
- {
- printf("send failed: %d\n", WSAGetLastError());
- closesocket(ConnectSocket);
- WSACleanup();
- return 1;
- }
- printf("Bytes Sent: %ld\n", iResult);
- // shutdown the connection for sending since no more data will be sent
- // the client can still use the ConnectSocket for receiving data
- iResult = shutdown(ConnectSocket, SD_SEND);
- if (iResult == SOCKET_ERROR)
- {
- printf("shutdown failed: %d\n", WSAGetLastError());
- closesocket(ConnectSocket);
- WSACleanup();
- return 1;
- }
- // Receive data until the server closes the connection
- do
- {
- iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
- if (iResult > 0)
- printf("Bytes received: %d\n", iResult);
- else if (iResult == 0)
- printf("Connection closed\n");
- else
- printf("recv failed: %d\n", WSAGetLastError());
- }
- while (iResult > 0);
- closesocket(ConnectSocket);
- WSACleanup();
- }
Add Comment
Please, Sign In to add comment