Skip to content

Commit

Permalink
add tk_socket_get_port
Browse files Browse the repository at this point in the history
  • Loading branch information
xianjimli committed Jul 9, 2024
1 parent 812189e commit f9e06fd
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
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/09
* 增加函数 tk\_socket\_get\_port (感谢智明提供补丁)

2024/07/05
* 修改assets\_manager\_unref没有释放资源列表中的数据问题和增加注释(感谢智明提供补丁)

Expand Down
10 changes: 10 additions & 0 deletions src/tkc/socket_helper.c
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ ret_t tk_socket_bind(int sock, int port) {
return tk_socket_bind_ex(sock, NULL, port);
}

int tk_socket_get_port(int sock) {
struct sockaddr_in serv_addr;
socklen_t serv_addr_len = sizeof(serv_addr);

if (getsockname(sock, (struct sockaddr *)&serv_addr, &serv_addr_len) >= 0) {
return ntohs(serv_addr.sin_port);
}
return -1;
}

int tk_tcp_listen(int port) {
int sock;
int on = 1;
Expand Down
10 changes: 10 additions & 0 deletions src/tkc/socket_helper.h
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,16 @@ const char* tk_socket_get_self_ip_str(int sockfd, char* ip, int len);
*/
int tk_tcp_listen(int port);

/**
* @method tk_socket_get_port
* @annotation ["static"]
* 获取当前 socket 的监听指定端口。
* @param {int} port 端口号。
*
* @return {int} 成功返回端口,失败返回 -1。
*/
int tk_socket_get_port(int sock);

/**
* @method tk_tcp_accept
* @annotation ["static"]
Expand Down

0 comments on commit f9e06fd

Please sign in to comment.