Skip to content
Snippets Groups Projects
Commit 0f8ef0c2 authored by Stéphane Del Pino's avatar Stéphane Del Pino
Browse files

Find automatically a free port when 0 is given as an argument

This follows the C standard. This is particularly useful for unit
testing socket interface.
parent e7e80742
No related branches found
No related tags found
1 merge request!126Begin socket handling: core functionalities are available
...@@ -55,6 +55,12 @@ class Socket::Internals ...@@ -55,6 +55,12 @@ class Socket::Internals
return m_is_server_socket; return m_is_server_socket;
} }
int
portNumber() const
{
return ::ntohs(m_address.sin_port);
}
int int
fileDescriptor() const fileDescriptor() const
{ {
...@@ -83,6 +89,12 @@ operator<<(std::ostream& os, const Socket& socket) ...@@ -83,6 +89,12 @@ operator<<(std::ostream& os, const Socket& socket)
return os << *socket.m_internals; return os << *socket.m_internals;
} }
int
Socket::portNumber() const
{
return m_internals->portNumber();
}
Socket Socket
createServerSocket(int port_number) createServerSocket(int port_number)
{ {
...@@ -101,8 +113,14 @@ createServerSocket(int port_number) ...@@ -101,8 +113,14 @@ createServerSocket(int port_number)
int on = 1; int on = 1;
::setsockopt(socket_internals.m_socket_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); ::setsockopt(socket_internals.m_socket_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if (::bind(socket_internals.m_socket_fd, reinterpret_cast<sockaddr*>(&socket_internals.m_address), socklen_t length = sizeof(socket_internals.m_address);
sizeof(socket_internals.m_address)) < 0) {
if (::bind(socket_internals.m_socket_fd, reinterpret_cast<sockaddr*>(&socket_internals.m_address), length) < 0) {
throw NormalError(strerror(errno));
}
if (::getsockname(socket_internals.m_socket_fd, reinterpret_cast<sockaddr*>(&socket_internals.m_address), &length) ==
-1) {
throw NormalError(strerror(errno)); throw NormalError(strerror(errno));
} }
......
...@@ -19,6 +19,8 @@ class Socket ...@@ -19,6 +19,8 @@ class Socket
void _read(char* data, const size_t lenght) const; void _read(char* data, const size_t lenght) const;
public: public:
int portNumber() const;
friend std::ostream& operator<<(std::ostream& os, const Socket& s); friend std::ostream& operator<<(std::ostream& os, const Socket& s);
friend Socket createServerSocket(int port_number); friend Socket createServerSocket(int port_number);
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment