socket.connect() loops over addresses returned by getaddrinfo

This commit is contained in:
Diego Nehab 2012-04-23 01:29:41 +08:00
parent f960b3872a
commit 966642f76a

View File

@ -19,21 +19,31 @@ function connect(address, port, laddress, lport)
if address == "*" then address = "0.0.0.0" end if address == "*" then address = "0.0.0.0" end
local addrinfo, err = socket.dns.getaddrinfo(address); local addrinfo, err = socket.dns.getaddrinfo(address);
if not addrinfo then return nil, err end if not addrinfo then return nil, err end
local sock, err; local err = "no info on address"
if addrinfo[1].family == "inet" then local sock, res
for i, alt in base.ipairs(addrinfo) do
if alt.family == "inet" then
sock, err = socket.tcp() sock, err = socket.tcp()
else else
sock, err = socket.tcp6() sock, err = socket.tcp6()
end end
if not sock then return nil, err end if not sock then return nil, err end
if laddress then if laddress then
local res, err = sock:bind(laddress, lport, -1) res, err = sock:bind(laddress, lport)
if not res then return nil, err end if not res then
sock:close()
return nil, err
end end
local res, err = sock:connect(address, port) end
if not res then return nil, err end res, err = sock:connect(alt.addr, port)
if not res then
sock:close()
else
return sock return sock
end end
end
return nil, err
end
function bind(host, port, backlog) function bind(host, port, backlog)
if host == "*" then host = "0.0.0.0" end if host == "*" then host = "0.0.0.0" end