udp: listen on default multicast interface (#4565) (#4820)

... instead of listening on all multicast interfaces.
This commit is contained in:
Alessandro Ros
2025-08-04 15:18:48 +02:00
committed by GitHub
parent 4390b87524
commit 914220d974
2 changed files with 47 additions and 8 deletions
+1 -1
View File
@@ -913,7 +913,7 @@ paths:
The resulting stream is available in path `/mypath`.
If the listening IP is a multicast IP, _MediaMTX_ listens for incoming multicast packets on all network interfaces. It is possible to listen on a single interface only by using the `interface` parameter:
If the listening IP is a multicast IP, _MediaMTX_ listens for incoming multicast packets on the default interface picked by the operating system. It is possible to specify this interface manually by using the `interface` parameter:
```yml
paths:
+46 -7
View File
@@ -24,6 +24,44 @@ const (
udpKernelReadBufferSize = 0x80000
)
func defaultInterfaceForMulticast(multicastAddr *net.UDPAddr) (*net.Interface, error) {
conn, err := net.Dial("udp4", multicastAddr.String())
if err != nil {
return nil, err
}
localAddr := conn.LocalAddr().(*net.UDPAddr)
conn.Close()
interfaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, iface := range interfaces {
var addrs []net.Addr
addrs, err = iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip != nil && ip.Equal(localAddr.IP) {
return &iface, nil
}
}
}
return nil, fmt.Errorf("could not find any interface for using multicast address %s", multicastAddr)
}
type packetConnReader struct {
pc net.PacketConn
sourceIP net.IP
@@ -90,23 +128,24 @@ func (s *Source) Run(params defs.StaticSourceRunParams) error {
var pc packetConn
if ip4 := addr.IP.To4(); ip4 != nil && addr.IP.IsMulticast() {
var intf *net.Interface
if intfName := q.Get("interface"); intfName != "" {
var intf *net.Interface
intf, err = net.InterfaceByName(intfName)
if err != nil {
return err
}
pc, err = multicast.NewSingleConn(intf, addr.String(), net.ListenPacket)
if err != nil {
return err
}
} else {
pc, err = multicast.NewMultiConn(addr.String(), true, net.ListenPacket)
intf, err = defaultInterfaceForMulticast(addr)
if err != nil {
return err
}
}
pc, err = multicast.NewSingleConn(intf, addr.String(), net.ListenPacket)
if err != nil {
return err
}
} else {
var tmp net.PacketConn
tmp, err = net.ListenPacket(restrictnetwork.Restrict("udp", addr.String()))