UDPServer.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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(IPv4Address const& 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. ErrorOr<size_t> send(ReadonlyBytes, sockaddr_in const& to);
  27. Optional<IPv4Address> local_address() const;
  28. Optional<u16> local_port() const;
  29. int fd() const { return m_fd; }
  30. Function<void()> on_ready_to_receive;
  31. protected:
  32. explicit UDPServer(Object* parent = nullptr);
  33. private:
  34. int m_fd { -1 };
  35. bool m_bound { false };
  36. RefPtr<Notifier> m_notifier;
  37. };
  38. }