Serenity Operating System
1/*
2 * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
3 * Copyright (c) 2022, Alexander Narsudinov <a.narsudinov@gmail.com>
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 */
7
8#pragma once
9
10#include <AK/ByteBuffer.h>
11#include <AK/Forward.h>
12#include <AK/Function.h>
13#include <LibCore/Forward.h>
14#include <LibCore/Object.h>
15#include <LibCore/SocketAddress.h>
16
17namespace Core {
18
19class UDPServer : public Object {
20 C_OBJECT(UDPServer)
21public:
22 virtual ~UDPServer() override;
23
24 bool is_bound() const { return m_bound; }
25
26 bool bind(IPv4Address const& address, u16 port);
27 ErrorOr<ByteBuffer> receive(size_t size, sockaddr_in& from);
28 ErrorOr<ByteBuffer> receive(size_t size)
29 {
30 struct sockaddr_in saddr;
31 return receive(size, saddr);
32 };
33
34 ErrorOr<size_t> send(ReadonlyBytes, sockaddr_in const& to);
35
36 Optional<IPv4Address> local_address() const;
37 Optional<u16> local_port() const;
38
39 int fd() const { return m_fd; }
40
41 Function<void()> on_ready_to_receive;
42
43protected:
44 explicit UDPServer(Object* parent = nullptr);
45
46private:
47 int m_fd { -1 };
48 bool m_bound { false };
49 RefPtr<Notifier> m_notifier;
50};
51
52}