Skip to content

Commit

Permalink
feat(socket): automatically detects the IP address type for connect
Browse files Browse the repository at this point in the history
The `ipv6` parameter do not required previously used to indicate use IPv6 connection.

Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Apr 16, 2024
1 parent 35ca0ec commit 6269331
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
18 changes: 16 additions & 2 deletions socket.lua
Original file line number Diff line number Diff line change
Expand Up @@ -268,10 +268,22 @@ function M.listen_tcp(ipaddr, port, options)
return sock:listen(options.backlog)
end

local function ipaddr_to_family(ipaddr)
if socket.is_ipv4_address(ipaddr) then
return socket.AF_INET
elseif socket.is_ipv6_address(ipaddr) then
return socket.AF_INET6
else
return nil
end
end

function M.connect_tcp(ipaddr, port, options)
options = options or {}

local family = options.ipv6 and socket.AF_INET6 or socket.AF_INET
local family = ipaddr_to_family(ipaddr)

assert(family, 'not a valid IP address')

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

local family = options.ipv6 and socket.AF_INET6 or socket.AF_INET
local family = ipaddr_to_family(ipaddr)

assert(family, 'not a valid IP address')

local sock, err = M.socket(family, socket.SOCK_DGRAM, nil, options)
if not sock then
Expand Down
2 changes: 1 addition & 1 deletion ssh.lua
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ function M.new(ipaddr, port, username, password)
return nil, 'invalid ipaddr: ' .. ipaddr
end

local sock, err = socket.connect_tcp(ipaddr, port, { ipv6 = socket.is_ipv6_address(ipaddr) })
local sock, err = socket.connect_tcp(ipaddr, port)
if not sock then
return nil, err
end
Expand Down

0 comments on commit 6269331

Please sign in to comment.