Переглянути джерело

add: udpsrv返回对端的ip和端口,仅ipv4地址

https://gitee.com/openLuat/LuatOS/issues/I87938
Wendal Chen 2 роки тому
батько
коміт
91beee5a0a
2 змінених файлів з 12 додано та 5 видалено
  1. 4 3
      demo/socket/udp_server/main.lua
  2. 8 2
      script/libs/udpsrv.lua

+ 4 - 3
demo/socket/udp_server/main.lua

@@ -62,13 +62,14 @@ sys.taskInit(function()
     local srv = udpsrv.create(12345, mytopic)
     if srv then
         -- 单播
-        srv:send("I am UP", "192.168.1.16", 777)
+        srv:send("I am UP", "192.168.1.12", 777)
         -- 广播
         srv:send("I am UP", "255.255.255.255", 777)
         while 1 do
-            local ret, data = sys.waitUntil(mytopic, 15000)
+            local ret, data, remote_ip, remote_port = sys.waitUntil(mytopic, 15000)
             if ret then
-                log.info("udpsrv", "收到数据", data:toHex())
+                -- remote_ip, remote_port 是2023.10.12新增的返回值
+                log.info("udpsrv", "收到数据", data:toHex(), remote_ip, remote_port)
                 -- 按业务处理收到的数据
             else
                 log.info("udpsrv", "没数据,那广播一条")

+ 8 - 2
script/libs/udpsrv.lua

@@ -32,11 +32,17 @@ function udpsrv.create(port, topic, adapter)
         if event == socket.EVENT then
             local rxbuff = srv.rxbuff
             while 1 do
-                local succ, data_len = socket.rx(sc, rxbuff)
+                local succ, data_len, remote_ip, remote_port = socket.rx(sc, rxbuff)
                 if succ and data_len and data_len > 0 then
                     local resp = rxbuff:toStr(0, rxbuff:used())
                     rxbuff:del()
-                    sys.publish(topic, resp)
+                    if remote_ip and #remote_ip == 5 then
+                        local ip1,ip2,ip3,ip4 = remote_ip:byte(2),remote_ip:byte(3),remote_ip:byte(4),remote_ip:byte(5)
+                        remote_ip = string.format("%d.%d.%d.%d", ip1, ip2, ip3, ip4)
+                    else
+                        remote_ip = nil
+                    end
+                    sys.publish(topic, resp, remote_ip, remote_port)
                 else
                     break
                 end