SocketAddress.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/IPv4Address.h>
  9. #include <arpa/inet.h>
  10. #include <netinet/in.h>
  11. #include <string.h>
  12. #include <sys/socket.h>
  13. #include <sys/un.h>
  14. namespace Core {
  15. class SocketAddress {
  16. public:
  17. enum class Type {
  18. Invalid,
  19. IPv4,
  20. Local
  21. };
  22. SocketAddress() = default;
  23. SocketAddress(IPv4Address const& address)
  24. : m_type(Type::IPv4)
  25. , m_ipv4_address(address)
  26. {
  27. }
  28. SocketAddress(IPv4Address const& address, u16 port)
  29. : m_type(Type::IPv4)
  30. , m_ipv4_address(address)
  31. , m_port(port)
  32. {
  33. }
  34. static SocketAddress local(DeprecatedString const& address)
  35. {
  36. SocketAddress addr;
  37. addr.m_type = Type::Local;
  38. addr.m_local_address = address;
  39. return addr;
  40. }
  41. Type type() const { return m_type; }
  42. bool is_valid() const { return m_type != Type::Invalid; }
  43. IPv4Address ipv4_address() const { return m_ipv4_address; }
  44. u16 port() const { return m_port; }
  45. DeprecatedString to_deprecated_string() const
  46. {
  47. switch (m_type) {
  48. case Type::IPv4:
  49. return DeprecatedString::formatted("{}:{}", m_ipv4_address, m_port);
  50. case Type::Local:
  51. return m_local_address;
  52. default:
  53. return "[SocketAddress]";
  54. }
  55. }
  56. Optional<sockaddr_un> to_sockaddr_un() const
  57. {
  58. VERIFY(type() == Type::Local);
  59. sockaddr_un address;
  60. address.sun_family = AF_LOCAL;
  61. bool fits = m_local_address.copy_characters_to_buffer(address.sun_path, sizeof(address.sun_path));
  62. if (!fits)
  63. return {};
  64. return address;
  65. }
  66. sockaddr_in to_sockaddr_in() const
  67. {
  68. VERIFY(type() == Type::IPv4);
  69. sockaddr_in address {};
  70. address.sin_family = AF_INET;
  71. address.sin_addr.s_addr = m_ipv4_address.to_in_addr_t();
  72. address.sin_port = htons(m_port);
  73. return address;
  74. }
  75. private:
  76. Type m_type { Type::Invalid };
  77. IPv4Address m_ipv4_address;
  78. u16 m_port { 0 };
  79. DeprecatedString m_local_address;
  80. };
  81. }
  82. template<>
  83. struct AK::Formatter<Core::SocketAddress> : Formatter<DeprecatedString> {
  84. ErrorOr<void> format(FormatBuilder& builder, Core::SocketAddress const& value)
  85. {
  86. return Formatter<DeprecatedString>::format(builder, value.to_deprecated_string());
  87. }
  88. };