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.
This commit is contained in:
Xu Jun 2023-02-22 18:59:13 +08:00 committed by GitHub
parent d2772c4153
commit 92c4bbebad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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: