Skip to content

Commit

Permalink
impove socket helper allow listen port 0
Browse files Browse the repository at this point in the history
  • Loading branch information
xianjimli committed Jul 4, 2024
1 parent 6be26d7 commit 3a8ae12
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
3 changes: 3 additions & 0 deletions docs/changes.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# 最新动态

2024/07/04
* 完善 socket_helper.c,允许listen端口为0,系统自动分配端口。

2024/07/02
* 修复 awtk-web 部分键值冲突的问题。

Expand Down
11 changes: 10 additions & 1 deletion src/tkc/socket_helper.c
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ ret_t tk_socket_close(int sock) {

ret_t tk_socket_bind_ex(int sock, const char* ip, int port) {
struct sockaddr_in s;
return_value_if_fail(sock >= 0 && port > 0, RET_BAD_PARAMS);
return_value_if_fail(sock >= 0 && port >= 0, RET_BAD_PARAMS);

memset(&s, 0, sizeof(s));

Expand Down Expand Up @@ -131,6 +131,15 @@ int tk_tcp_listen(int port) {
return -1;
}

if (port == 0) {
struct sockaddr_in serv_addr;
socklen_t serv_addr_len = sizeof(serv_addr);

if (getsockname(sock, (struct sockaddr *)&serv_addr, &serv_addr_len) >= 0) {
log_debug("port is 0, system auto allocted port is %d\n", ntohs(serv_addr.sin_port));
}
}

return (sock);
}

Expand Down

0 comments on commit 3a8ae12

Please sign in to comment.