Return CNetAddr for the specified OS-level network address. If a length is not given, it is taken to be sizeof(struct sockaddr_*) for the family.
| 39 | //! Return CNetAddr for the specified OS-level network address. |
| 40 | //! If a length is not given, it is taken to be sizeof(struct sockaddr_*) for the family. |
| 41 | std::optional<CNetAddr> FromSockAddr(const struct sockaddr* addr, std::optional<socklen_t> sa_len_opt) |
| 42 | { |
| 43 | socklen_t sa_len = 0; |
| 44 | if (sa_len_opt.has_value()) { |
| 45 | sa_len = *sa_len_opt; |
| 46 | } else { |
| 47 | // If sockaddr length was not specified, determine it from the family. |
| 48 | switch (addr->sa_family) { |
| 49 | case AF_INET: sa_len = sizeof(struct sockaddr_in); break; |
| 50 | case AF_INET6: sa_len = sizeof(struct sockaddr_in6); break; |
| 51 | default: |
| 52 | return std::nullopt; |
| 53 | } |
| 54 | } |
| 55 | // Fill in a CService from the sockaddr, then drop the port part. |
| 56 | CService service; |
| 57 | if (service.SetSockAddr(addr, sa_len)) { |
| 58 | return (CNetAddr)service; |
| 59 | } |
| 60 | return std::nullopt; |
| 61 | } |
| 62 | |
| 63 | // Linux and FreeBSD 14.0+. For FreeBSD 13.2 the code can be compiled but |
| 64 | // running it requires loading a special kernel module, otherwise socket(AF_NETLINK,...) |
no test coverage detected