Skip to content

Conversation

@Siomachkin
Copy link
Contributor

@Siomachkin Siomachkin commented Sep 13, 2025

Implements GitHub issue #6856 - adds support for binding Caddy listeners to network interfaces by name instead of requiring specific IP addresses.

Features

  • Interface name binding: Use `bind "eth0" instead of hardcoded IP addresses
  • IP version modes:
    • Single-address modes: bind "eth0:8080:firstipv4" (first IPv4), bind "eth0:8080:firstipv6" (first IPv6), bind "eth0:8080:auto" (prefer IPv4, fallback to IPv6)
    • Multi-address modes: bind "eth0:8080:ipv4" (all IPv4), bind "eth0:8080:ipv6" (all IPv6), bind "eth0:8080:all" (all addresses)

Usage Examples

Basic Interface Binding

example.com {
    bind "eth0"  # Binds to first available IP on eth0 interface
    respond "Hello from eth0!"
}

With Specific Ports and IP Version Modes

  # First IPv4 only (single listener)
  api.example.com {
      bind "eth0:8080:firstipv4"
      respond "First IPv4 API"
  }

  # First IPv6 only (single listener)
  api-v6.example.com {
      bind "eth0:8080:firstipv6"
      respond "First IPv6 API"
  }

  # Auto mode (prefers first IPv4, falls back to first IPv6)
  auto.example.com {
      bind "eth0:8080:auto"  # Default mode
      respond "Auto-selected IP"
  }

  # IPv4 mode (binds to ALL IPv4 addresses on the interface)
  ipv4.example.com {
      bind "eth0:8080:ipv4"
      respond "All IPv4 addresses"
  }

  # IPv6 mode (binds to ALL IPv6 addresses on the interface)
  ipv6.example.com {
      bind "eth0:8080:ipv6"
      respond "All IPv6 addresses"
  }

  # All mode (binds to ALL IPs on the interface, both IPv4 and IPv6)
  all.example.com {
      bind "eth0:8080:all"
      respond "All IPs on interface"
  }

Key Functions

  • isInterfaceName(): Validates interface names and handles interface:port:mode patterns
  • selectIPByMode(): Chooses appropriate IP address based on binding mode
  • resolveInterfaceNameWithMode(): Resolves interface names to IP addresses
  • parseInterfaceAddress(): Parses and validates interface binding syntax

Testing

  • Unit tests for all parsing and validation logic

Assistance Disclosure
I consulted Claude to understand the project architecture, but I authored/coded the fix myself.

@francislavoie francislavoie changed the title Add Network Interface Binding Support with IP Version Modes listeners: Add network interface binding support, with IP version modes Sep 13, 2025
@francislavoie
Copy link
Member

More interface names to test:

  • br-901e40e4488d
  • enx9cbf0d00631a
  • veth1308dcd
  • fe80:: IPv6 that has a starting letter (hex)

@francislavoie francislavoie added the feature ⚙️ New feature or request label Sep 14, 2025
@francislavoie francislavoie added this to the v2.11.0 milestone Sep 14, 2025
@Monviech
Copy link
Contributor

Monviech commented Oct 6, 2025

Im interested in this, thats why Im asking some questions.

Why does it bind to only a single IP address per interface (the first), and not all of the available ones on an interface? Especially for IPv6 there could be a link local address, one or multiple GUAs (with and without privacy extension) and possibly even ULAs. IPv4 can also have virtual IPs on the same interface.

Also what happens if IP addresses change during runtime, e.g. DHCPv4 and v6 leases on ISP provided WAN interfaces (and by extension SLAAC prefix changes), does Caddy notice that the runtime environment changed and reload with the updated addresses? Or will it crash, or stop to serve until manually restarted?

@francislavoie
Copy link
Member

This looks good to me at this stage. I'd like to see @Monviech's comments addressed though, before we merge.

@Monviech
Copy link
Contributor

Reading the initial issue the problem is that they use DHCP and do not know which IP address the server gets.

That is easily solvable by binding caddy to localhost (127.0.0.1 or ::1), and using a NAT rule on the same system to redirect traffic from their interface to localhost where caddy listens. Doing that also outsources to iptables/pf/ipfw or whatever firewall they can configure in their system to keep track of the interface IP address dynamically, so even if their IP changes during runtime caddy will continue to work because, well, its bound to localhost.

I'm just saying that binding to an interface IP address is a lot more ambiguous in caddy than setting an IP address (or localhost e.g. 127.0.0.1 or ::1) which nobody writing the config can misinterpret.

@Siomachkin
Copy link
Contributor Author

@Monviech Thanks for the detailed feedback!

Regarding binding to all IPs: I'm working on adding support for bind "eth0:8080:all" to bind to all addresses on
an interface, which would address the multiple IPs scenario you mentioned.

Regarding runtime IP changes: If the interface IP changes during runtime:

  • Caddy won't crash, but it will likely stop accepting new connections since the listener is bound to an IP that no
    longer exists on the interface
  • A caddy reload would be required to rebind to the new IP
  • Monitoring network interface changes and automatically rebinding is a more complex feature that would require
    separate design work

Regarding the NAT/localhost approach: That's a valid alternative for truly dynamic IPs, but it requires
platform-specific firewall configuration and root privileges. This feature provides a simpler, cross-platform solution
for common scenarios where:

  • IPs are stable (DHCP with long/infinite leases)
  • IP changes happen infrequently (at provisioning time)
  • Users prefer declarative Caddyfile configuration over external system setup

The original issue and follow-up comments show multiple users specifically requesting this interface binding syntax.

@Monviech
Copy link
Contributor

@Siomachkin Thank you for explaining the constraints. Offering an "all" mode for an interface sounds like a great idea. :)

@francislavoie
Copy link
Member

Re runtime IP changes, I think we can just leave it to the user to reload, and we can mention it in the docs for this feature that they should do a force reload if they're making networking config changes. (btw a simple reload isn't enough if the Caddy config hasn't changed, would need reload --force).

I'll wait for the all addition, then I think we're ready to merge.

Comment on lines 45 to 57
const (
// MaxInterfaceNameUnix represents the maximum interface name length on Unix-like systems
// Based on IFNAMSIZ = 16 (15 characters + null terminator)
MaxInterfaceNameUnix = 15

// MaxInterfaceNameWindows represents the maximum interface name length on Windows
// These systems use a more complex naming structure with MAX_ADAPTER_NAME_LENGTH allowing 256 characters
MaxInterfaceNameWindows = 255
)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can unexport these? Only used in this file

Copy link
Member

@francislavoie francislavoie left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM aside from any exported names cleanup, also merging your other PR caused a conflict that needs to be resolved.

@Monviech I'd like your 👍 as well if you would

@Monviech
Copy link
Contributor

I didnt look much at the code but from the concept the 'all' mode should be the one with the least asumptions which is nice.

Just the 'all' mode would be enough (for me). But thats just my perspective.

I mean if there is one IPv4 address on an interface, all does the same job as single address mode. If two IPv4 addresses are on the same interface, it already assumes with the single address mode, but all is perfectly explainable. Same for IPv6, or a mix of both. And auto is also a little random.

All (dual stack), all ipv4, all ipv6 would be with the least weirdness, I assume.

Go ahead though, Im just rambling :)

@Siomachkin
Copy link
Contributor Author

@Monviech Thanks for the thoughtful feedback! I understand your point about 'all' mode having the least assumptions.

However, I believe the single-address modes (ipv4/ipv6/auto) serve important use cases:

  1. Simplicity for common cases: Looking back at the original issue, all use cases needed to bind to a single interface address (internal network, Tailscale) without knowing the specific IP in advance. The single-address modes directly solve these real-world scenarios - binding to one stable address per interface, not creating multiple listeners for every address.
  2. Security: Principle of least privilege - bind only to what's actually needed.

The 'all' mode is great when you genuinely need all addresses, but having single-address modes gives users flexibility. Both approaches serve different needs.

If you think it would be useful, I could also add allipv4 and allipv6 modes for completeness.

@francislavoie
Copy link
Member

francislavoie commented Oct 22, 2025

Maybe more like firstipv4, firstipv6, ipv4, ipv6, all ? Sounds to me like using all IPs as default may be more sensible?

@Monviech
Copy link
Contributor

Monviech commented Oct 23, 2025

(Im not a maintainer or project owner here so pleasing me is entirely optional and can be seen as consulting from a network guys perspective)

In my opinion too much choice bloats the code and confuses the user.

Also the first address is a very elusive concept, it can be quite random.

And then we are back at "but I want to choose a specific IP address on that specific interface, or I want to configure a range (eg cidr) of allowed IP addresses for which listeners can be opened if there are multiple choices on that interface.

And then the all mode is essentially the most predictable and explainable choice. It puts the responsibility on the admin who configures the interface, not on caddy to assume many different diverging cases.

Look at how other projects bind to interface, e.g. dnsmasq (which is around since quite some time). I know that caddy isnt dnsmasq or another service, but looking at how another service handles this could be interesting when choosing the design.

From their man page:

-z, --bind-interfaces
On systems which support it, dnsmasq binds the wildcard address, even when it is listening on only some interfaces. It then discards requests that it shouldn't reply to. This has the advantage of working even when interfaces come and go and change address. This option forces dnsmasq to really bind only the interfaces it is listening on. About the only time when this is useful is when running another nameserver (or another instance of dnsmasq) on the same machine. Setting this option also enables multiple instances of dnsmasq which provide DHCP service to run in the same machine.

Copy link
Member

@mholt mholt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM -- although I think the |~| delimiter is weird; something like || feels a bit cleaner but, I don't have a strong enough opinion on it.

Only thing I would suggest is let's document the functionality as experimental so we could change it if needed.

@francislavoie
Copy link
Member

So in the end I'm kinda confused, what's the || thing for, I don't see it used anywhere in the test coverage. Should there be tests for that?

@Siomachkin
Copy link
Contributor Author

@francislavoie The || delimiter is used internally to encode the interface name and mode into the NetworkAddress.Host field.

The flow is:

  1. User writes: bind "eth0:8080:ipv4" in Caddyfile
  2. parseInterfaceAddress() parses this and encodes it as: Host = "eth0||ipv4" (using InterfaceDelimiter constant)
  3. Later, listenInterface() decodes it back by splitting on || to get interface name and mode.

The tests use InterfaceDelimiter constant, so they implicitly test the || encoding.

@francislavoie
Copy link
Member

Thanks

Can you quickly rebase it once again, then we can merge?

@MayCXC
Copy link
Contributor

MayCXC commented Oct 23, 2025

Are custom networks not the right syntax for this? We can use iface/name for what name:8080:all does here, iface4/name for what name:8080:ipv4 does, and iface6/name for what name:8080:ipv6 does, and use the port from the site block. This also allows for ifacegram ifacegram4 and ifacegram6 for UDP.

The first and auto modes are strange to me, I think a user would always configure the host OS network for something like this. For linux that would be ifcfg, an iptables/nftables redirect, systemd.socket with FreeBind and the fd networks (which also stays decoupled from iface with BindToDevice), etc. Unless it has a really good use case, I dislike the nondeterminism of binding to a single unknown address selected by caddy at runtime.

@Siomachkin Siomachkin force-pushed the feature/interface-binding branch from fe7d5fd to d732222 Compare October 24, 2025 06:45
@Siomachkin
Copy link
Contributor Author

@MayCXC Thanks for the thoughtful feedback!

However, this would require a complete architectural refactor of an already-approved implementation.

@mholt @francislavoie - What's your preference? Proceed with current approach or refactor to custom networks? I'm open to either direction.

@mholt
Copy link
Member

mholt commented Nov 3, 2025

Allow me a day or two (hopefully not much longer) to review and give some input here :)

@GustavoWidman
Copy link

i've tried using this branch for a while now and it's been awesome, i just wanted to give a simple suggestion based on my experience: when the desired interface is not up yet (or has no IPs assigned yet), maybe wait/keep service down instead of fully crashing/panicking (similar to how routing is currently handled to services whose ports are not answering/open yet)

@mholt
Copy link
Member

mholt commented Nov 18, 2025

Thanks for the suggestion @GustavoWidman -- that's good feedback. I don't know how difficult that would be to do...

I did have a chance to give this a once-over, and overall the code looks pretty good. I am still trying to decide if this approach is the best, or if we should expand the bind directive to include more configuration surface, like by opening a block. Currently we're trying to cram a lot into a single string.

@MayCXC
Copy link
Contributor

MayCXC commented Nov 18, 2025

@GustavoWidman are you able to execute caddy from a shell script like:

#!/bin/sh
IFACE=eth0

while ! ip -o addr show dev "$IFACE" | grep -q 'inet'; do
    sleep 1
done

exec caddy ...

@MayCXC
Copy link
Contributor

MayCXC commented Nov 18, 2025

@mholt @Siomachkin my primary concern with this implementation is that the port is now in the bind argument. why is it not still taken from the site block / how does that work for port ranges / does the same apply for default_bind?

@Monviech
Copy link
Contributor

Trying to avoid crashing if an interface is not yet available or does not yet have an IP address is the exact reason a wildcard bind exists.

Binding to the wildcard and filtering afterwards is always the superior choice.

@GustavoWidman
Copy link

GustavoWidman commented Nov 18, 2025

@GustavoWidman are you able to execute caddy from a shell script like:

#!/bin/sh
IFACE=eth0

while ! ip -o addr show dev "$IFACE" | grep -q 'inet'; do
    sleep 1
done

exec caddy ...

yes, of course, however, my usecase is super specific here: it's where one interface DEPENDS on caddy being up already to exist. on the machine i'm having issues with, i run my headscale server and THEN expose certain sites on only the tailscale0 interface. that means that the headscale server has to be running for tailscale to be brought up and then tailscale0 obtains an IP. of course, i could always just... run two caddy instances, but it's just a issue i experienced and thought the feedback might be helpful

@GustavoWidman
Copy link

Trying to avoid crashing if an interface is not yet available or does not yet have an IP address is the exact reason a wildcard bind exists.

Binding to the wildcard and filtering afterwards is always the superior choice.

not always, in a usecase where i absolutely cannot risk binding a sensitive service to public interfaces but also have to bind public services to the public interfaces themselves, i'd much rather bind it ONLY to a private interface

@Monviech
Copy link
Contributor

But that sounds like a policy issue. It should be handled via a tool that can enforce policies on packets like a firewall. Binding to loopback is already possible for example and its generic in all OSes. And firewall implementations are also generic and be used for policies that can send traffic to these sockets.

The main issue seems to be that people who do not have the correct privileges on these machines try to circumvent the need for tools that enforce network policies.

@GustavoWidman
Copy link

But that sounds like a policy issue. It should be handled via a tool that can enforce policies on packets like a firewall. Binding to loopback is already possible for example and its generic in all OSes. And firewall implementations are also generic and be used for policies that can send traffic to these sockets.

The main issue seems to be that people who do not have the correct privileges on these machines try to circumvent the need for tools that enforce network policies.

having a firewall implies the possibility of it being breached. it's safer not to bind at all than to filter.

@GustavoWidman
Copy link

GustavoWidman commented Nov 18, 2025

anyways, my suggestion implies the usage of SO_BINDTODEVICE instead of the current implementation of discovering the IP addresses of a interface then binding to those as it seems like the only logical way of "not erroring when binding fully to an interface"

@MayCXC
Copy link
Contributor

MayCXC commented Nov 18, 2025

yes, and/or freebind for linux. systemd.socket can do both.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature ⚙️ New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants