Skip to content

Add dynamic port selection to avoid conflicts with other applications #493

@Kittywy

Description

@Kittywy

Problem

The application currently attempts to connect to port 1337, which is commonly used by other applications (e.g., Razer services). This causes connection failures when these applications are running.

Solution

Add a port scanning function that automatically selects an available port that isn't being used by other applications.

Code example

#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdexcept>
#include <vector>

#pragma comment(lib, "ws2_32.lib")

class WinsockGuard {
public:
    WinsockGuard() {
        if (WSAStartup(MAKEWORD(2, 2), &wsa_data_) != 0) {
            throw std::runtime_error("WSAStartup failed");
        }
    }
    ~WinsockGuard() { WSACleanup(); }
    
    WinsockGuard(const WinsockGuard&) = delete;
    WinsockGuard& operator=(const WinsockGuard&) = delete;

private:
    WSADATA wsa_data_{};
};

class PortScanner {
public:
    static int find_available(int preferred_port = 1337) {
        WinsockGuard guard;
        
        // Try preferred port first
        if (is_port_available(preferred_port)) {
            return preferred_port;
        }
        
        // Scan for alternative
        for (int port = preferred_port + 1; port <= 65535; ++port) {
            if (is_port_available(port)) {
                return port;
            }
        }
        
        throw std::runtime_error("No available ports found");
    }

private:
    static bool is_port_available(int port) {
        SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (sock == INVALID_SOCKET) return false;

        sockaddr_in addr{};
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
        addr.sin_port = htons(static_cast<u_short>(port));

        bool available = (bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == 0);
        closesocket(sock);
        
        return available;
    }
};

Usage

int main() {
    try {
        int port = PortScanner::find_available(1337);
        std::cout << "Using port: " << port << std::endl;
        // ... start your server on this port
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions