-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathudp_server.cpp
More file actions
61 lines (51 loc) · 1.59 KB
/
udp_server.cpp
File metadata and controls
61 lines (51 loc) · 1.59 KB
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
#include "socket_util.h"
#include "peer_manager.h"
using namespace std;
void startUDPServer()
{
srand(time(0));
cout << "Server" << endl;
int listenSocket=createUDPIPv4Socket();
if (listenSocket < 0) {
cout << "Socket creation failed" << endl;
return ;
}
sockaddr_in trackeraddr=createIPv4Address("0.0.0.0",PORT);
if (bind(listenSocket, reinterpret_cast<sockaddr*>(&trackeraddr), sizeof(trackeraddr)) < 0) {
cout << "Bind error" << endl;
close(listenSocket);
return;
}
char buffer[4096];
sockaddr_in clientAddr;
socklen_t addrLen=sizeof(clientAddr);
while (true) {
int bytesRcvd = recvfrom(listenSocket, buffer, sizeof(buffer), 0,(sockaddr*)&clientAddr,&addrLen);
cout << "Message from client: " << endl;
for(size_t i=0; i<bytesRcvd;i++)
{
printf("%02x",(unsigned char)buffer[i]);
}
cout<<endl;
cout << "Client connected" << endl;
if (bytesRcvd <= 0) {
cout << "Client disconnected" << endl;
break;
}
if (bytesRcvd >= 12) {
uint32_t action;
memcpy(&action, buffer + 8, sizeof(uint32_t));
action = ntohl(action);
if (action == ACTION_CONNECT)
{
handleConnectRequest(buffer, bytesRcvd, listenSocket, clientAddr, addrLen);
}
else if(action==ACTION_ANNOUNCE)
{
processAnnounceRequest(buffer, bytesRcvd, listenSocket,clientAddr);
}
}
}
close(listenSocket);
return;
}