109 lines
2.7 KiB
C++

#include <cstdint>
#include <ctype.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib") // only needed for MSVC
#else
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include "server_structs.h"
#include "socket.h"
// Cross-platform close macro
#ifdef _WIN32
#define CLOSESOCKET closesocket
#else
#define CLOSESOCKET close
#endif
const int SERVER_OUT_PORT = 9996;
const int SERVER_IN_PORT = 11000;
const char* SERVER_OUT_IP = "127.0.0.1";
int main() {
#ifdef _WIN32
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
fprintf(stderr, "[-] WSAStartup failed\n");
return -1;
}
#endif
printf("[+] Starting server...\n");
printf("[+] Server listening on port %d\n", SERVER_IN_PORT);
printf("[+] Server sending to %s:%d\n", SERVER_OUT_IP, SERVER_OUT_PORT);
// Create UDP socket
int sock_FD = connect_udp_socket(SERVER_OUT_IP, SERVER_OUT_PORT);
if (sock_FD < 0) {
fprintf(stderr, "[-] Failed to create UDP socket\n");
#ifdef _WIN32
WSACleanup();
#endif
return -1;
}
handshake hs;
hs.identifier = 1;
hs.operationId = 1;
hs.version = 0;
printf("[+] Sending handshake message...\t");
ssize_t bytes_sent = send_udp_message((int)sock_FD, (const char*)&hs, SERVER_OUT_IP, uint16_t(SERVER_OUT_PORT));
if (bytes_sent >= 0) {
printf("OK (%zd bytes)\n", bytes_sent);
} else {
fprintf(stderr, "ERROR.\n");
CLOSESOCKET(sock_FD);
#ifdef _WIN32
WSACleanup();
#endif
return -2;
}
uint8_t buffer[512]; // bigger than struct
ssize_t bytes_received = recv(sock_FD, (char*)buffer, sizeof(buffer), 0);
if (bytes_received >= sizeof(handshackerResponse)) {
// Convert strings from big endian to little endian if necessary
handshackerResponse resp;
memcpy(&resp, buffer, sizeof(handshackerResponse));
printf("[+] Received handshake response:\n");
printf(" Car: ");
for (int i = 0; i < 50; i++) {
printf("%c", isprint(resp.carName[i]) ? resp.carName[i] : '.');
}
printf("\n");
printf(" Driver: %s\n", resp.driverName);
printf(" Identifier: %d\n", resp.identifier);
printf(" Version: %d\n", resp.version);
printf(" Track: %s\n", resp.trackName);
printf(" Config: %s\n", resp.trackConfig);
} else {
printf("[!] Packet too short for handshake response (%zd bytes)\n", bytes_received);
}
CLOSESOCKET(sock_FD);
#ifdef _WIN32
WSACleanup();
#endif
return 0;
}