-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
92 lines (70 loc) · 2.33 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Coded by Kirisan Manivannan
// Credit to: Sloan Kelley; https://www.youtube.com/watch?v=WDn-htpBlnU
// TCP-Server
#include <iostream>
#include <WS2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
void main() {
// Initialze winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsOk = WSAStartup(ver, &wsData);
if (wsOk != 0) {
cerr << "Can't Initialize winsock! Quitting" << endl;
return;
}
// Create a socket
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET) {
cerr << "Can't create a socket! Quitting" << endl;
return;
}
// Bind the IP address and port to a socket
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54000); // htons = host to network short
hint.sin_addr.S_un.S_addr = INADDR_ANY; // Could also use inet_pton...
bind(listening, (sockaddr*)&hint, sizeof(hint));
// Tell winsock the socket is for listening
listen(listening, SOMAXCONN);
// Wait for a connection
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize);
char host[NI_MAXHOST]; // Client's remote name
char service[NI_MAXHOST]; // Service (i.e port) the client is connect on
ZeroMemory(host, NI_MAXHOST);
ZeroMemory(service, NI_MAXHOST);
if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0) {
cout << host << " Connected on port " << service << endl;
}
else {
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << " Connected on port " <<
ntohs(client.sin_port) << endl; // ntohs = network to host short
}
// Close listening socket
closesocket(listening);
// While loop: accept and echo message back to client
char buf[4096];
while (true) {
ZeroMemory(buf, 4096);
// Wait for client to send data
int bytesReceived = recv(clientSocket, buf, 4096, 0);
if (bytesReceived == SOCKET_ERROR) {
cerr << "Error in recv(). Quitting" << endl;
break;
}
if (bytesReceived == 0) {
cout << "Client disconnected " << endl;
break;
}
// Echo message back to client
send(clientSocket, buf, bytesReceived + 1, 0);
}
// Close the sock
closesocket(clientSocket);
// Cleanup winsock
WSACleanup();
}