From 92c4bbebadb1589bda96d4365300723e06082dde Mon Sep 17 00:00:00 2001 From: Xu Jun <693788454@qq.com> Date: Wed, 22 Feb 2023 18:59:13 +0800 Subject: [PATCH] Fix getting port issue in posix os_socket_bind (#1981) In the previous code, the `*port` is assigned before `getsockname`, so the caller may be not able to get the actual port number assigned by system. Move the assigning of `*port` to be after `getsockname` to resolve the issue. --- .../platform/common/posix/posix_socket.c | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/core/shared/platform/common/posix/posix_socket.c b/core/shared/platform/common/posix/posix_socket.c index d9ec9d76..b058cebe 100644 --- a/core/shared/platform/common/posix/posix_socket.c +++ b/core/shared/platform/common/posix/posix_socket.c @@ -156,17 +156,6 @@ os_socket_bind(bh_socket_t socket, const char *host, int *port) goto fail; } - if (addr.ss_family == AF_INET) { - *port = ntohs(((struct sockaddr_in *)&addr)->sin_port); - } - else { -#ifdef IPPROTO_IPV6 - *port = ntohs(((struct sockaddr_in6 *)&addr)->sin6_port); -#else - goto fail; -#endif - } - ret = fcntl(socket, F_SETFD, FD_CLOEXEC); if (ret < 0) { goto fail; @@ -187,6 +176,17 @@ os_socket_bind(bh_socket_t socket, const char *host, int *port) goto fail; } + if (addr.ss_family == AF_INET) { + *port = ntohs(((struct sockaddr_in *)&addr)->sin_port); + } + else { +#ifdef IPPROTO_IPV6 + *port = ntohs(((struct sockaddr_in6 *)&addr)->sin6_port); +#else + goto fail; +#endif + } + return BHT_OK; fail: