Index: sys/dev/if_wg/module/if_wg_session.c =================================================================== --- sys/dev/if_wg/module/if_wg_session.c +++ sys/dev/if_wg/module/if_wg_session.c @@ -359,8 +359,6 @@ struct sockaddr_in6 *sin6; struct ifnet *ifp; - if (so->so_port == 0) - return (0); td = curthread; bzero(&laddr, sizeof(laddr)); ifp = iflib_get_ifp(sc->wg_ctx); @@ -374,6 +372,19 @@ if_printf(ifp, "can't bind AF_INET socket %d\n", rc); return (rc); } + + if (so->so_port == 0) { + rc = sosockaddr(so->so_so4, (struct sockaddr **)&sin); + if (rc != 0) { + if_printf(ifp, + "can't fetch listening port from socket, error %d\n", + rc); + return (rc); + } + + so->so_port = ntohs(sin->sin_port); + } + sin6 = &laddr.in6; sin6->sin6_len = sizeof(laddr.in6); sin6->sin6_family = AF_INET6; Index: sys/dev/if_wg/module/module.c =================================================================== --- sys/dev/if_wg/module/module.c +++ sys/dev/if_wg/module/module.c @@ -179,13 +179,11 @@ err = EBADMSG; goto out; } - if (!nvlist_exists_number(nvl, "listen-port")) { - device_printf(dev, "%s listen-port not set\n", __func__); - err = EBADMSG; - goto nvl_out; - } - listen_port = nvlist_get_number(nvl, "listen-port"); + /* wg_socket_bind() will update with the chosen port if omitted. */ + listen_port = 0; + if (nvlist_exists_number(nvl, "listen-port")) + listen_port = nvlist_get_number(nvl, "listen-port"); if (!nvlist_exists_binary(nvl, "private-key")) { device_printf(dev, "%s private-key not set\n", __func__); err = EBADMSG;