inets httpd官方示例无法运行及IPv6绑定问题咨询
Hey there! Let's break down and fix the two problems you're facing with Erlang's httpd service:
1. Invalid document_root Option Error
First up, that "invalid option" error for document_root is almost always tied to a simple configuration structure issue or syntax mistake:
Wrong config nesting: Ensure
document_rootis placed inside theserver_configsection if you're using the modern httpd API. Your config should follow this structure:Config = [ {server_root, "/tmp/httpd"}, {server_name, "localhost"}, {bind_address, {127,0,0,1}}, {port, 8080}, {server_config, [ {document_root, "/path/to/your/documents"}, {directory_index, ["index.html"]} ]} ], httpd:start(Config).If you put
document_rootat the top level (outsideserver_config), httpd will reject it as an invalid option.Outdated example mismatch: If you copied code from an older inets user guide, the syntax might have changed with newer Erlang/OTP versions (especially post-OTP 24). Double-check that your guide matches your installed Erlang version.
Typos or syntax errors: A missing comma, mismatched bracket, or misspelled option (like
document_root_instead ofdocument_root) can trigger this error. Do a quick pass to verify your config tuple's syntax.
2. Troubleshooting IPv6 Localhost Binding
The confusion around ip_address()'s N and K parameters comes from how Erlang represents IPv6 addresses. Here's the clear, practical breakdown:
Erlang's inet:ip_address() type for IPv6 has two valid formats:
- A tuple of 8 16-bit integers (each between 0 and 65535), which maps to the 128-bit IPv6 address. For localhost (
::1), this translates to{0,0,0,0,0,0,0,1}. - A plain string representation of the IPv6 address (e.g.,
"::1"or"2001:db8::1").
Correct IPv6 Config Examples
To bind to IPv6 localhost, use either of these valid setups:
% Using tuple format for ::1 Config = [ {server_root, "/tmp/httpd"}, {server_name, "localhost"}, {bind_address, {ipv6, {0,0,0,0,0,0,0,1}}}, {port, 8080}, {server_config, [ {document_root, "/path/to/your/documents"} ]} ], httpd:start(Config).
Or:
% Using string format for ::1 Config = [ {server_root, "/tmp/httpd"}, {server_name, "localhost"}, {bind_address, {ipv6, "::1"}}, {port, 8080}, {server_config, [ {document_root, "/path/to/your/documents"} ]} ], httpd:start(Config).
Additional Checks
- System IPv6 support: Confirm your OS has IPv6 enabled (most modern systems do, but verify with
ip addr showon Linux orifconfigon macOS to see if::1appears in the loopback interface). - Firewall rules: Make sure your firewall isn't blocking incoming connections on the port you're using for IPv6.
- OTP version compatibility: Older Erlang versions (pre-OTP 20) had limited IPv6 support for httpd—consider upgrading if you're on a very old release.
If you're still hitting errors, share your exact config and error message, and we can dig deeper!
内容的提问来源于stack exchange,提问作者7stud

