UDPServer.h 1019 B

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