Browse files

socket.bind also tries all addresses returned by getaddrinfo.

  • Loading branch information...
1 parent 966642f commit 1acf8188cd732de4fd5fcdc016eeab501c86a773 @diegonehab diegonehab committed Apr 22, 2012
Showing with 25 additions and 14 deletions.
  1. +2 −1 TODO
  2. +23 −13 src/socket.lua
View
3 TODO
@@ -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
@@ -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?
View
36 src/socket.lua
@@ -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()
@@ -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()

0 comments on commit 1acf818

Please sign in to comment.