Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core: add iface as network type #6506

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions interface.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package caddy

import (
"context"
"fmt"
"net"
"strings"
)

func init() {
RegisterNetwork("iface", getInterfaceListener)
RegisterNetwork("iface+tcp", getInterfaceListener)
RegisterNetwork("iface+udp", getInterfaceListener)
}

func getInterfaceListener(ctx context.Context, network, addr string, config net.ListenConfig) (any, error) {
// assuming addr = "interface+family:port"
// if family is missing, then assume tcp
family := "tcp"
parts := strings.Split(network, "+")
if len(parts) == 2 {
family = parts[1]
}
host, port, _ := net.SplitHostPort(addr)
iface, err := net.InterfaceByName(host)
if err != nil {
return nil, fmt.Errorf("interface %s not found", addr)
}
addrs, err := iface.Addrs()
if err != nil {
return nil, fmt.Errorf("error on obtaining interface %s addresses: %s", iface.Name, err)
}
if len(addrs) == 0 {
return nil, fmt.Errorf("interface %s has no addresses", iface.Name)
}
for _, addr := range addrs {
if face, ok := addr.(*net.IPNet); ok {
if ip4 := face.IP.To4(); ip4 != nil {
switch family {
case "tcp":
return net.Listen(family, net.JoinHostPort(ip4.String(), port))
case "udp":
return net.ListenPacket(family, net.JoinHostPort(ip4.String(), port))
default:
return net.Listen(family, net.JoinHostPort(ip4.String(), port))
}
}
}
}
return nil, fmt.Errorf("interface %s has no IPv4 addresses", iface.Name)
}
4 changes: 4 additions & 0 deletions modules/caddyhttp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ import (
"github.com/caddyserver/caddy/v2/modules/caddytls"
)

func init() {
RegisterNetworkHTTP3("iface", "iface+udp")
}

// Server describes an HTTP server.
type Server struct {
// Socket addresses to which to bind listeners. Accepts
Expand Down
Loading