| 1 |
// Copyright 2011 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
//go:build (unix && !linux) || windows |
| 6 |
|
| 7 |
package net |
| 8 |
|
| 9 |
import ( |
| 10 |
"internal/bytealg" |
| 11 |
"runtime" |
| 12 |
"syscall" |
| 13 |
) |
| 14 |
|
| 15 |
func joinIPv4Group(fd *netFD, ifi *Interface, ip IP) error { |
| 16 |
mreq := &syscall.IPMreq{Multiaddr: [4]byte{ip[0], ip[1], ip[2], ip[3]}} |
| 17 |
if err := setIPv4MreqToInterface(mreq, ifi); err != nil { |
| 18 |
return err |
| 19 |
} |
| 20 |
err := fd.pfd.SetsockoptIPMreq(syscall.IPPROTO_IP, syscall.IP_ADD_MEMBERSHIP, mreq) |
| 21 |
runtime.KeepAlive(fd) |
| 22 |
return wrapSyscallError("setsockopt", err) |
| 23 |
} |
| 24 |
|
| 25 |
func setIPv4MreqToInterface(mreq *syscall.IPMreq, ifi *Interface) error { |
| 26 |
if ifi == nil { |
| 27 |
return nil |
| 28 |
} |
| 29 |
ifat, err := ifi.Addrs() |
| 30 |
if err != nil { |
| 31 |
return err |
| 32 |
} |
| 33 |
for _, ifa := range ifat { |
| 34 |
switch v := ifa.(type) { |
| 35 |
case *IPAddr: |
| 36 |
if a := v.IP.To4(); a != nil { |
| 37 |
copy(mreq.Interface[:], a) |
| 38 |
goto done |
| 39 |
} |
| 40 |
case *IPNet: |
| 41 |
if a := v.IP.To4(); a != nil { |
| 42 |
copy(mreq.Interface[:], a) |
| 43 |
goto done |
| 44 |
} |
| 45 |
} |
| 46 |
} |
| 47 |
done: |
| 48 |
if bytealg.Equal(mreq.Interface[:], IPv4zero.To4()) { |
| 49 |
return errNoSuchMulticastInterface |
| 50 |
} |
| 51 |
return nil |
| 52 |
} |