SHOW:
|
|
- or go back to the newest paste.
1 | #ifndef WIN32_LEAN_AND_MEAN | |
2 | #define WIN32_LEAN_AND_MEAN | |
3 | #endif | |
4 | ||
5 | #include <iostream> | |
6 | #include <fstream> | |
7 | #include <Windows.h> | |
8 | ||
9 | #include <WinSock2.h> | |
10 | #include <WS2tcpip.h> | |
11 | #include <iphlpapi.h> | |
12 | #include <stdio.h> | |
13 | ||
14 | using namespace std; | |
15 | ||
16 | #pragma comment(lib, "Ws2_32.lib") | |
17 | ||
18 | ||
19 | #define PORT_NUMBER 1337 | |
20 | ||
21 | #define SERVER_ADDRESS "localhost" | |
22 | #define BUFFER_LENGTH 500 | |
23 | ||
24 | int ShowError(); | |
25 | ||
26 | int main() | |
27 | { | |
28 | ||
29 | WSADATA wsaData; | |
30 | ||
31 | int Result; | |
32 | ||
33 | Result = WSAStartup(MAKEWORD(2, 2), &wsaData); | |
34 | ||
35 | if (Result != 0) | |
36 | { | |
37 | WSACleanup(); | |
38 | return ShowError(); | |
39 | } | |
40 | ||
41 | SOCKET ClientSocket = INVALID_SOCKET; | |
42 | ||
43 | ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | |
44 | ||
45 | if (ClientSocket == INVALID_SOCKET) | |
46 | { | |
47 | WSACleanup(); | |
48 | return ShowError(); | |
49 | } | |
50 | ||
51 | struct hostent* host; | |
52 | ||
53 | host = gethostbyname(SERVER_ADDRESS); | |
54 | ||
55 | if (host == 0) | |
56 | { | |
57 | WSACleanup(); | |
58 | return ShowError(); | |
59 | } | |
60 | ||
61 | SOCKADDR_IN SockAddr; | |
62 | ||
63 | SockAddr.sin_family = AF_INET; | |
64 | SockAddr.sin_port = htons(PORT_NUMBER); | |
65 | ||
66 | unsigned long* address = (unsigned long*)host->h_addr; | |
67 | ||
68 | SockAddr.sin_addr.s_addr = *address; | |
69 | ||
70 | ||
71 | ||
72 | Result = connect(ClientSocket, (SOCKADDR*)&SockAddr, sizeof(SockAddr)); | |
73 | ||
74 | if (Result == SOCKET_ERROR) | |
75 | { | |
76 | WSACleanup(); | |
77 | return ShowError(); | |
78 | } | |
79 | ||
80 | ||
81 | char ReceiveBuffer[BUFFER_LENGTH]; | |
82 | memset(ReceiveBuffer, 0, BUFFER_LENGTH-1); | |
83 | ||
84 | int length = BUFFER_LENGTH; | |
85 | ||
86 | int bReceived = 0; //bytes received | |
87 | ||
88 | do | |
89 | { | |
90 | bReceived = recv(ClientSocket, ReceiveBuffer, length, 0); | |
91 | ||
92 | if (bReceived > 0) | |
93 | { | |
94 | printf("\n\nBytes Received: %d\n", bReceived); | |
95 | printf("Received Buffer: %s\n", ReceiveBuffer); | |
96 | } | |
97 | ||
98 | } while (bReceived > 0); | |
99 | ||
100 | ||
101 | printf("Closing connection...\n\n"); | |
102 | ||
103 | shutdown(ClientSocket, SD_SEND); | |
104 | ||
105 | closesocket(ClientSocket); | |
106 | ||
107 | WSACleanup(); | |
108 | ||
109 | system("PAUSE > NUL"); | |
110 | ||
111 | return 0; | |
112 | } | |
113 | ||
114 | ||
115 | int ShowError() | |
116 | { | |
117 | MessageBox(NULL, "An error occured.", 0, 0); | |
118 | return 1; | |
119 | } |