File: testUtils.cpp

package info (click to toggle)
cpr 1.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,452 kB
  • sloc: cpp: 14,315; ansic: 637; sh: 139; xml: 38; makefile: 16
file content (70 lines) | stat: -rw-r--r-- 1,697 bytes parent folder | download
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
#include "testUtils.hpp"

#include <cstdint>
#include <stdexcept>

#ifdef _WIN32
#define NOMINMAX
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#endif

namespace cpr::test {

std::uint16_t get_free_port() {
#ifdef _WIN32
    static const WSAInit wsa_guard; // one-time Winsock init
#endif

    // 1. Create a TCP socket.
    socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sock == INVALID_SOCKET_FD) {
        throw std::runtime_error("socket() failed");
    }

    // 2. Bind to port 0 so the OS assigns an ephemeral port.
    sockaddr_in addr{};
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(0); // 0 ⇒ “pick for me”

    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
    if (::bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
#ifdef _WIN32
        ::closesocket(sock);
#else
        ::close(sock);
#endif
        throw std::runtime_error("bind() failed");
    }

    // 3. Ask what port we actually got.
    socklen_t len = sizeof(addr);
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
    if (::getsockname(sock, reinterpret_cast<sockaddr*>(&addr), &len) != 0) {
#ifdef _WIN32
        ::closesocket(sock);
#else
        ::close(sock);
#endif
        throw std::runtime_error("getsockname() failed");
    }

    std::uint16_t port = ntohs(addr.sin_port);

    // 4. Close the socket ‒ we only needed it to grab the port number.
#ifdef _WIN32
    ::closesocket(sock);
#else
    ::close(sock);
#endif

    return port;
}
} // namespace cpr::test