Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
markaren committed May 16, 2024
1 parent 1ca1495 commit d51a07a
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
3 changes: 2 additions & 1 deletion include/AvailablePortQuery.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
#ifndef SIMPLE_SOCKET_AVAILABLEPORTQUERY_HPP
#define SIMPLE_SOCKET_AVAILABLEPORTQUERY_HPP

#include <vector>

int getAvailablePort(int startPort, int endPort);
int getAvailablePort(int startPort, int endPort, const std::vector<int>& excludePorts = {});

#endif//SIMPLE_SOCKET_AVAILABLEPORTQUERY_HPP
8 changes: 7 additions & 1 deletion src/AvailablePortQuery.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@

#include "SocketIncludes.hpp"

#include <algorithm>

int getAvailablePort(int startPort, int endPort) {
int getAvailablePort(int startPort, int endPort, const std::vector<int>& excludePorts) {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == SOCKET_ERROR) {
return -1;
Expand All @@ -18,6 +19,11 @@ int getAvailablePort(int startPort, int endPort) {
serv_addr.sin_addr.s_addr = INADDR_ANY;

for (int port = startPort; port <= endPort; ++port) {

if (std::find(excludePorts.begin(), excludePorts.end(), port) != excludePorts.end()) {
continue;
}

serv_addr.sin_port = htons(port);
if (bind(sockfd, reinterpret_cast<sockaddr*>(&serv_addr), sizeof(serv_addr)) != SOCKET_ERROR) {
closeSocket(sockfd);
Expand Down
8 changes: 6 additions & 2 deletions tests/test_udp.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@

#include "UDPSocket.hpp"
#include "WSASession.hpp"
#include "AvailablePortQuery.hpp"

#include <catch2/catch_test_macros.hpp>

Expand All @@ -9,8 +10,11 @@ TEST_CASE("Test UDP") {
WSASession session;

std::string address{"127.0.0.1"};
int serverPort = 8070;
int clientPort = 8071;
int serverPort = getAvailablePort(8000, 9000);
int clientPort = getAvailablePort(8000, 9000, {serverPort});

REQUIRE(serverPort != -1);
REQUIRE(clientPort != -1);

UDPSocket socket1(serverPort);
UDPSocket socket2(clientPort);
Expand Down

0 comments on commit d51a07a

Please sign in to comment.