Skip to content

Commit

Permalink
socket.bind also tries all addresses returned by getaddrinfo.
Browse files Browse the repository at this point in the history
  • Loading branch information
diegonehab committed Apr 22, 2012
1 parent 966642f commit 1acf818
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
3 changes: 2 additions & 1 deletion TODO
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
- document bind and connect behavior.
- getsockname should also support IPv6, no?
- shouldn't we instead make the code compatible to Lua 5.2
without any compat stuff, and use a compatibility layer to
make it work on 5.1?
- add what's new to manual
- should there be an equivalent to tohostname for IPv6?
- should we add service name resolution as well to getaddrinfo?
- document bind and connect behavior based on address?

- add http POST sample to manual
people keep asking stupid questions
Expand All @@ -16,6 +16,7 @@

Done:

- connect and bind try all adresses returned by getaddrinfo
- document headers.lua?
- update copyright date everywhere?
- remove RCSID from files?
Expand Down
36 changes: 23 additions & 13 deletions src/socket.lua
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ function connect(address, port, laddress, lport)
if address == "*" then address = "0.0.0.0" end
local addrinfo, err = socket.dns.getaddrinfo(address);
if not addrinfo then return nil, err end
local err = "no info on address"
local sock, res
err = "no info on address"
for i, alt in base.ipairs(addrinfo) do
if alt.family == "inet" then
sock, err = socket.tcp()
Expand Down Expand Up @@ -49,19 +49,29 @@ function bind(host, port, backlog)
if host == "*" then host = "0.0.0.0" end
local addrinfo, err = socket.dns.getaddrinfo(host);
if not addrinfo then return nil, err end
local sock, err;
if addrinfo[1].family == "inet" then
sock, err = socket.tcp()
else
sock, err = socket.tcp6()
local sock, res
err = "no info on address"
for i, alt in base.ipairs(addrinfo) do
if alt.family == "inet" then
sock, err = socket.tcp()
else
sock, err = socket.tcp6()
end
if not sock then return nil, err end
sock:setoption("reuseaddr", true)
res, err = sock:bind(alt.addr, port)
if not res then
sock:close()
else
res, err = sock:listen(backlog)
if not res then
sock:close()
else
return sock
end
end
end
if not sock then return nil, err end
sock:setoption("reuseaddr", true)
local res, err = sock:bind(host, port)
if not res then return nil, err end
res, err = sock:listen(backlog)
if not res then return nil, err end
return sock
return nil, err
end

try = newtry()
Expand Down

0 comments on commit 1acf818

Please sign in to comment.