add multicast.InterfaceForSource (#414)

This commit is contained in:
Alessandro Ros
2023-09-11 23:53:22 +02:00
committed by GitHub
parent 78198a588b
commit 4ede58cda2
2 changed files with 32 additions and 31 deletions

View File

@@ -2,6 +2,7 @@
package multicast
import (
"fmt"
"net"
)
@@ -10,3 +11,33 @@ type Conn interface {
net.PacketConn
SetReadBuffer(int) error
}
// InterfaceForSource returns a multicast-capable interface that can communicate with given IP.
func InterfaceForSource(ip net.IP) (*net.Interface, error) {
if ip.Equal(net.ParseIP("127.0.0.1")) {
return nil, fmt.Errorf("IP 127.0.0.1 can't be used as source of a multicast stream. Use the LAN IP of your PC")
}
intfs, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, intf := range intfs {
if (intf.Flags & net.FlagMulticast) == 0 {
continue
}
addrs, err := intf.Addrs()
if err == nil {
for _, addr := range addrs {
_, ipnet, err := net.ParseCIDR(addr.String())
if err == nil && ipnet.Contains(ip) {
return &intf, nil
}
}
}
}
return nil, fmt.Errorf("found no interface that is multicast-capable and can communicate with IP %v", ip)
}