-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
86 lines (75 loc) · 2.46 KB
/
main.c
File metadata and controls
86 lines (75 loc) · 2.46 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
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
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#include "Tracker.h"
#pragma comment(lib, "ws2_32.lib")
void PrintClientHostnameAndPort(SOCKADDR_IN clientAddr) {
char hostname[16] = { 0 };
inet_ntop(AF_INET, &clientAddr.sin_addr, hostname, 16);
printf("%s:%u ", hostname, swap16(clientAddr.sin_port));
}
int Run(TrackerContext* ctx) {
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 2);
int err;
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0) {
printf("WSAStartup failed with error: %d\n", err);
return 1;
}
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
printf("Could not find a usable version of Winsock.dll\n");
WSACleanup();
return 1;
}
SOCKET serverSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (serverSocket == INVALID_SOCKET) {
printf("socket creation failed with error: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
SOCKADDR_IN serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(6969);
if (bind(serverSocket, (LPSOCKADDR)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
closesocket(serverSocket);
WSACleanup();
return 1;
}
printf("UDP server is listening on port 6969\n");
char buf[1500];
SOCKADDR_IN clientAddr;
int addrLen = sizeof(clientAddr);
int txLen, recvLen;
while (1) {
recvLen = recvfrom(serverSocket, buf, sizeof(buf), 0, (LPSOCKADDR)&clientAddr, &addrLen);
if (recvLen == SOCKET_ERROR) {
printf("recvfrom failed with error: %d\n", WSAGetLastError());
break;
}
PrintClientHostnameAndPort(clientAddr);
HandleClientRequestV4(ctx, clientAddr.sin_addr.s_addr, buf, recvLen, buf, &txLen);
if (txLen != -1) {
sendto(serverSocket, buf, txLen, 0, (LPSOCKADDR)&clientAddr, addrLen);
}
}
closesocket(serverSocket);
WSACleanup();
}
int main() {
uint32_t NUM_OF_SUPPORT_PEERS = 16384;
uint32_t NUM_OF_SUPPORT_TORRENTS = 16384;
TrackerContextConfig cfg = {
.announceInterval = 15 * 60,
.numOfSupportPeers = NUM_OF_SUPPORT_PEERS,
.numOfSupportTorrents = NUM_OF_SUPPORT_TORRENTS,
};
printf("Non-intelligent BitTorrent tracker server\n");
TrackerContext* ctx = CreateTrackerServer(&cfg);
if (ctx) { Run(ctx); DeinitTrackerServer(ctx); }
else { printf("Create tracker server is failure.\n"); }
return 0;
}