Skip to content

Commit 6269331

Browse files
committed
feat(socket): automatically detects the IP address type for connect
The `ipv6` parameter do not required previously used to indicate use IPv6 connection. Signed-off-by: Jianhui Zhao <[email protected]>
1 parent 35ca0ec commit 6269331

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

socket.lua

+16-2
Original file line numberDiff line numberDiff line change
@@ -268,10 +268,22 @@ function M.listen_tcp(ipaddr, port, options)
268268
return sock:listen(options.backlog)
269269
end
270270

271+
local function ipaddr_to_family(ipaddr)
272+
if socket.is_ipv4_address(ipaddr) then
273+
return socket.AF_INET
274+
elseif socket.is_ipv6_address(ipaddr) then
275+
return socket.AF_INET6
276+
else
277+
return nil
278+
end
279+
end
280+
271281
function M.connect_tcp(ipaddr, port, options)
272282
options = options or {}
273283

274-
local family = options.ipv6 and socket.AF_INET6 or socket.AF_INET
284+
local family = ipaddr_to_family(ipaddr)
285+
286+
assert(family, 'not a valid IP address')
275287

276288
local sock, err = M.socket(family, socket.SOCK_STREAM, nil, options)
277289
if not sock then
@@ -297,7 +309,9 @@ end
297309
function M.connect_udp(ipaddr, port, options)
298310
options = options or {}
299311

300-
local family = options.ipv6 and socket.AF_INET6 or socket.AF_INET
312+
local family = ipaddr_to_family(ipaddr)
313+
314+
assert(family, 'not a valid IP address')
301315

302316
local sock, err = M.socket(family, socket.SOCK_DGRAM, nil, options)
303317
if not sock then

ssh.lua

+1-1
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,7 @@ function M.new(ipaddr, port, username, password)
424424
return nil, 'invalid ipaddr: ' .. ipaddr
425425
end
426426

427-
local sock, err = socket.connect_tcp(ipaddr, port, { ipv6 = socket.is_ipv6_address(ipaddr) })
427+
local sock, err = socket.connect_tcp(ipaddr, port)
428428
if not sock then
429429
return nil, err
430430
end

0 commit comments

Comments
 (0)