From c7a9c71456844b164477f329f79f5e10de7898a4 Mon Sep 17 00:00:00 2001
From: yangchen <yangchen145@huawei.com>
Date: Wed, 15 Nov 2023 11:23:04 +0800
Subject: [PATCH] wrap: fix connect wrong port after addr bind two ports

---
 src/lstack/api/lstack_wrap.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/src/lstack/api/lstack_wrap.c b/src/lstack/api/lstack_wrap.c
index 5bad513..f427d33 100644
--- a/src/lstack/api/lstack_wrap.c
+++ b/src/lstack/api/lstack_wrap.c
@@ -219,7 +219,20 @@ static int32_t do_bind(int32_t s, const struct sockaddr *name, socklen_t namelen
 
     if (match_host_addr(((struct sockaddr_in *)name)->sin_addr.s_addr)) {
         /* maybe kni addr */
-        posix_api->bind_fn(s, name, namelen);
+        if (posix_api->bind_fn(s, name, namelen) != 0) {
+            SET_CONN_TYPE_LIBOS(sock->conn);
+        } else {
+            /* reuse the port allocated by kernel when port == 0 */
+            if (((struct sockaddr_in *)name)->sin_port == 0) {
+                struct sockaddr_in kerneladdr;
+                socklen_t len = sizeof(kerneladdr);
+                if (posix_api->getsockname_fn(s, (struct sockaddr *)&kerneladdr, &len) < 0) {
+                    LSTACK_LOG(ERR, LSTACK, "kernel getsockname failed, fd=%d, errno=%d\n", s, errno);
+                    return -1;
+                }
+                ((struct sockaddr_in *)name)->sin_port = kerneladdr.sin_port;
+            }
+        }
         return g_wrap_api->bind_fn(s, name, namelen);
     } else {
         SET_CONN_TYPE_HOST(sock->conn);
-- 
2.27.0

