UDPServer.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. #pragma once
  8. #include <AK/ByteBuffer.h>
  9. #include <AK/Forward.h>
  10. #include <AK/Function.h>
  11. #include <LibCore/EventReceiver.h>
  12. #include <LibCore/Forward.h>
  13. #include <LibCore/SocketAddress.h>
  14. namespace Core {
  15. class UDPServer : public EventReceiver {
  16. C_OBJECT(UDPServer)
  17. public:
  18. virtual ~UDPServer() override;
  19. bool is_bound() const { return m_bound; }
  20. bool bind(IPv4Address const& address, u16 port);
  21. ErrorOr<ByteBuffer> receive(size_t size, sockaddr_in& from);
  22. ErrorOr<ByteBuffer> receive(size_t size)
  23. {
  24. struct sockaddr_in saddr;
  25. return receive(size, saddr);
  26. }
  27. ErrorOr<size_t> send(ReadonlyBytes, sockaddr_in const& to);
  28. Optional<IPv4Address> local_address() const;
  29. Optional<u16> local_port() const;
  30. int fd() const { return m_fd; }
  31. Function<void()> on_ready_to_receive;
  32. protected:
  33. explicit UDPServer(EventReceiver* parent = nullptr);
  34. private:
  35. int m_fd { -1 };
  36. bool m_bound { false };
  37. RefPtr<Notifier> m_notifier;
  38. };
  39. }