+// Get the port that `from_fd` is listening on, and assign it to
+// `sa` if `sa` has a dynamically allocated (zero) port.
+static bool assign_static_port(sockaddr_t *sa, int from_fd) {
+ // We cannot get a port from a bad FD. Bail out.
+ if(from_fd <= 0) {
+ return false;
+ }
+
+ int port = get_bound_port(from_fd);
+
+ if(!port) {
+ return false;
+ }
+
+ // If the port is non-zero, don't reassign it as it's already static.
+ switch(sa->sa.sa_family) {
+ case AF_INET:
+ if(!sa->in.sin_port) {
+ sa->in.sin_port = htons(port);
+ }
+
+ return true;
+
+ case AF_INET6:
+ if(!sa->in6.sin6_port) {
+ sa->in6.sin6_port = htons(port);
+ }
+
+ return true;
+
+ default:
+ logger(DEBUG_ALWAYS, LOG_ERR, "Unknown address family 0x%x", sa->sa.sa_family);
+ return false;
+ }
+}
+
+typedef int (*bind_fn_t)(const sockaddr_t *);
+
+static int bind_reusing_port(const sockaddr_t *sa, int from_fd, bind_fn_t setup) {
+ sockaddr_t reuse_sa;
+ memcpy(&reuse_sa, sa, SALEN(sa->sa));
+
+ int fd = -1;
+
+ // Check if the address we've been passed here is using port 0.
+ // If it is, try to get an actual port from an already bound socket, and reuse it here.
+ if(assign_static_port(&reuse_sa, from_fd)) {
+ fd = setup(&reuse_sa);
+ }
+
+ // If we're binding to a hardcoded non-zero port, or no socket is listening yet,
+ // or binding failed, try the original address.
+ if(fd < 0) {
+ fd = setup(sa);
+ }
+
+ return fd;
+}
+