2019-08-05 10:47:30 +00:00
|
|
|
#include <AK/IPv4Address.h>
|
|
|
|
#include <AK/Types.h>
|
2019-11-04 12:07:41 +00:00
|
|
|
#include <LibCore/CNotifier.h>
|
2019-08-05 10:47:30 +00:00
|
|
|
#include <LibCore/CTCPServer.h>
|
|
|
|
#include <LibCore/CTCPSocket.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <sys/socket.h>
|
|
|
|
|
|
|
|
CTCPServer::CTCPServer(CObject* parent)
|
|
|
|
: CObject(parent)
|
|
|
|
{
|
|
|
|
m_fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
|
|
|
|
ASSERT(m_fd >= 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
CTCPServer::~CTCPServer()
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
bool CTCPServer::listen(const IPv4Address& address, u16 port)
|
|
|
|
{
|
|
|
|
if (m_listening)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
int rc;
|
|
|
|
auto socket_address = CSocketAddress(address, port);
|
|
|
|
auto in = socket_address.to_sockaddr_in();
|
|
|
|
rc = ::bind(m_fd, (const sockaddr*)&in, sizeof(in));
|
|
|
|
ASSERT(rc == 0);
|
|
|
|
|
|
|
|
rc = ::listen(m_fd, 5);
|
|
|
|
ASSERT(rc == 0);
|
|
|
|
m_listening = true;
|
|
|
|
|
2019-09-21 13:18:12 +00:00
|
|
|
m_notifier = CNotifier::construct(m_fd, CNotifier::Event::Read);
|
2019-08-05 10:47:30 +00:00
|
|
|
m_notifier->on_ready_to_read = [this] {
|
|
|
|
if (on_ready_to_accept)
|
|
|
|
on_ready_to_accept();
|
|
|
|
};
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-09-21 22:31:54 +00:00
|
|
|
RefPtr<CTCPSocket> CTCPServer::accept()
|
2019-08-05 10:47:30 +00:00
|
|
|
{
|
|
|
|
ASSERT(m_listening);
|
|
|
|
sockaddr_in in;
|
|
|
|
socklen_t in_size = sizeof(in);
|
|
|
|
int accepted_fd = ::accept(m_fd, (sockaddr*)&in, &in_size);
|
|
|
|
if (accepted_fd < 0) {
|
|
|
|
perror("accept");
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
2019-09-21 08:13:34 +00:00
|
|
|
return CTCPSocket::construct(accepted_fd);
|
2019-08-05 10:47:30 +00:00
|
|
|
}
|
2019-10-07 08:07:24 +00:00
|
|
|
|
2019-11-04 12:07:41 +00:00
|
|
|
Optional<IPv4Address> CTCPServer::local_address() const
|
2019-10-07 08:07:24 +00:00
|
|
|
{
|
|
|
|
if (m_fd == -1)
|
|
|
|
return {};
|
|
|
|
|
|
|
|
sockaddr_in address;
|
|
|
|
socklen_t len = sizeof(address);
|
|
|
|
if (getsockname(m_fd, (sockaddr*)&address, &len) != 0)
|
2019-11-04 12:07:41 +00:00
|
|
|
return {};
|
2019-10-07 08:07:24 +00:00
|
|
|
|
|
|
|
return IPv4Address(address.sin_addr.s_addr);
|
|
|
|
}
|
|
|
|
|
2019-11-04 12:07:41 +00:00
|
|
|
Optional<u16> CTCPServer::local_port() const
|
2019-10-07 08:07:24 +00:00
|
|
|
{
|
|
|
|
if (m_fd == -1)
|
2019-11-04 12:07:41 +00:00
|
|
|
return {};
|
2019-10-07 08:07:24 +00:00
|
|
|
|
|
|
|
sockaddr_in address;
|
|
|
|
socklen_t len = sizeof(address);
|
|
|
|
if (getsockname(m_fd, (sockaddr*)&address, &len) != 0)
|
2019-11-04 12:07:41 +00:00
|
|
|
return {};
|
2019-10-07 08:07:24 +00:00
|
|
|
|
|
|
|
return ntohs(address.sin_port);
|
|
|
|
}
|