Involved Source Filesbatch.gocontrol.gocontrol_rfc3542_unix.gocontrol_unix.godgramopt.go Package ipv6 implements IP-level socket options for the Internet
Protocol version 6.
The package provides IP-level socket options that allow
manipulation of IPv6 facilities.
The IPv6 protocol is defined in RFC 8200.
Socket interface extensions are defined in RFC 3493, RFC 3542 and
RFC 3678.
MLDv1 and MLDv2 are defined in RFC 2710 and RFC 3810.
Source-specific multicast is defined in RFC 4607.
On Darwin, this package requires OS X Mavericks version 10.9 or
above, or equivalent.
# Unicasting
The options for unicasting are available for net.TCPConn,
net.UDPConn and net.IPConn which are created as network connections
that use the IPv6 transport. When a single TCP connection carrying
a data flow of multiple packets needs to indicate the flow is
important, Conn is used to set the traffic class field on the IPv6
header for each packet.
ln, err := net.Listen("tcp6", "[::]:1024")
if err != nil {
// error handling
}
defer ln.Close()
for {
c, err := ln.Accept()
if err != nil {
// error handling
}
go func(c net.Conn) {
defer c.Close()
The outgoing packets will be labeled DiffServ assured forwarding
class 1 low drop precedence, known as AF11 packets.
if err := ipv6.NewConn(c).SetTrafficClass(0x28); err != nil {
// error handling
}
if _, err := c.Write(data); err != nil {
// error handling
}
}(c)
}
# Multicasting
The options for multicasting are available for net.UDPConn and
net.IPConn which are created as network connections that use the
IPv6 transport. A few network facilities must be prepared before
you begin multicasting, at a minimum joining network interfaces and
multicast groups.
en0, err := net.InterfaceByName("en0")
if err != nil {
// error handling
}
en1, err := net.InterfaceByIndex(911)
if err != nil {
// error handling
}
group := net.ParseIP("ff02::114")
First, an application listens to an appropriate address with an
appropriate service port.
c, err := net.ListenPacket("udp6", "[::]:1024")
if err != nil {
// error handling
}
defer c.Close()
Second, the application joins multicast groups, starts listening to
the groups on the specified network interfaces. Note that the
service port for transport layer protocol does not matter with this
operation as joining groups affects only network and link layer
protocols, such as IPv6 and Ethernet.
p := ipv6.NewPacketConn(c)
if err := p.JoinGroup(en0, &net.UDPAddr{IP: group}); err != nil {
// error handling
}
if err := p.JoinGroup(en1, &net.UDPAddr{IP: group}); err != nil {
// error handling
}
The application might set per packet control message transmissions
between the protocol stack within the kernel. When the application
needs a destination address on an incoming packet,
SetControlMessage of PacketConn is used to enable control message
transmissions.
if err := p.SetControlMessage(ipv6.FlagDst, true); err != nil {
// error handling
}
The application could identify whether the received packets are
of interest by using the control message that contains the
destination address of the received packet.
b := make([]byte, 1500)
for {
n, rcm, src, err := p.ReadFrom(b)
if err != nil {
// error handling
}
if rcm.Dst.IsMulticast() {
if rcm.Dst.Equal(group) {
// joined group, do something
} else {
// unknown group, discard
continue
}
}
The application can also send both unicast and multicast packets.
p.SetTrafficClass(0x0)
p.SetHopLimit(16)
if _, err := p.WriteTo(data[:n], nil, src); err != nil {
// error handling
}
dst := &net.UDPAddr{IP: group, Port: 1024}
wcm := ipv6.ControlMessage{TrafficClass: 0xe0, HopLimit: 1}
for _, ifi := range []*net.Interface{en0, en1} {
wcm.IfIndex = ifi.Index
if _, err := p.WriteTo(data[:n], &wcm, dst); err != nil {
// error handling
}
}
}
# More multicasting
An application that uses PacketConn may join multiple multicast
groups. For example, a UDP listener with port 1024 might join two
different groups across over two different network interfaces by
using:
c, err := net.ListenPacket("udp6", "[::]:1024")
if err != nil {
// error handling
}
defer c.Close()
p := ipv6.NewPacketConn(c)
if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::1:114")}); err != nil {
// error handling
}
if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::2:114")}); err != nil {
// error handling
}
if err := p.JoinGroup(en1, &net.UDPAddr{IP: net.ParseIP("ff02::2:114")}); err != nil {
// error handling
}
It is possible for multiple UDP listeners that listen on the same
UDP port to join the same multicast group. The net package will
provide a socket that listens to a wildcard address with reusable
UDP port when an appropriate multicast address prefix is passed to
the net.ListenPacket or net.ListenUDP.
c1, err := net.ListenPacket("udp6", "[ff02::]:1024")
if err != nil {
// error handling
}
defer c1.Close()
c2, err := net.ListenPacket("udp6", "[ff02::]:1024")
if err != nil {
// error handling
}
defer c2.Close()
p1 := ipv6.NewPacketConn(c1)
if err := p1.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil {
// error handling
}
p2 := ipv6.NewPacketConn(c2)
if err := p2.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil {
// error handling
}
Also it is possible for the application to leave or rejoin a
multicast group on the network interface.
if err := p.LeaveGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil {
// error handling
}
if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff01::114")}); err != nil {
// error handling
}
# Source-specific multicasting
An application that uses PacketConn on MLDv2 supported platform is
able to join source-specific multicast groups.
The application may use JoinSourceSpecificGroup and
LeaveSourceSpecificGroup for the operation known as "include" mode,
ssmgroup := net.UDPAddr{IP: net.ParseIP("ff32::8000:9")}
ssmsource := net.UDPAddr{IP: net.ParseIP("fe80::cafe")}
if err := p.JoinSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil {
// error handling
}
if err := p.LeaveSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil {
// error handling
}
or JoinGroup, ExcludeSourceSpecificGroup,
IncludeSourceSpecificGroup and LeaveGroup for the operation known
as "exclude" mode.
exclsource := net.UDPAddr{IP: net.ParseIP("fe80::dead")}
if err := p.JoinGroup(en0, &ssmgroup); err != nil {
// error handling
}
if err := p.ExcludeSourceSpecificGroup(en0, &ssmgroup, &exclsource); err != nil {
// error handling
}
if err := p.LeaveGroup(en0, &ssmgroup); err != nil {
// error handling
}
Note that it depends on each platform implementation what happens
when an application which runs on MLDv2 unsupported platform uses
JoinSourceSpecificGroup and LeaveSourceSpecificGroup.
In general the platform tries to fall back to conversations using
MLDv1 and starts to listen to multicast traffic.
In the fallback case, ExcludeSourceSpecificGroup and
IncludeSourceSpecificGroup may return an error.endpoint.gogenericopt.goheader.gohelper.goiana.goicmp.goicmp_linux.gopayload.gopayload_cmsg.gosockopt.gosockopt_posix.gosys_asmreq.gosys_bpf.gosys_linux.gosys_ssmreq.gozsys_linux_amd64.go
Code Examples
package main
import (
"log"
"net"
"golang.org/x/net/ipv6"
)
func main() {
ln, err := net.Listen("tcp", "[::]:1024")
if err != nil {
log.Fatal(err)
}
defer ln.Close()
for {
c, err := ln.Accept()
if err != nil {
log.Fatal(err)
}
go func(c net.Conn) {
defer c.Close()
if c.RemoteAddr().(*net.TCPAddr).IP.To16() != nil && c.RemoteAddr().(*net.TCPAddr).IP.To4() == nil {
p := ipv6.NewConn(c)
if err := p.SetTrafficClass(0x28); err != nil { // DSCP AF11
log.Fatal(err)
}
if err := p.SetHopLimit(128); err != nil {
log.Fatal(err)
}
}
if _, err := c.Write([]byte("HELLO-R-U-THERE-ACK")); err != nil {
log.Fatal(err)
}
}(c)
}
}
package main
import (
"log"
"net"
"golang.org/x/net/ipv6"
)
func main() {
c, err := net.ListenPacket("ip6:89", "::") // OSPF for IPv6
if err != nil {
log.Fatal(err)
}
defer c.Close()
p := ipv6.NewPacketConn(c)
en0, err := net.InterfaceByName("en0")
if err != nil {
log.Fatal(err)
}
allSPFRouters := net.IPAddr{IP: net.ParseIP("ff02::5")}
if err := p.JoinGroup(en0, &allSPFRouters); err != nil {
log.Fatal(err)
}
defer p.LeaveGroup(en0, &allSPFRouters)
hello := make([]byte, 24) // fake hello data, you need to implement this
ospf := make([]byte, 16) // fake ospf header, you need to implement this
ospf[0] = 3 // version 3
ospf[1] = 1 // hello packet
ospf = append(ospf, hello...)
if err := p.SetChecksum(true, 12); err != nil {
log.Fatal(err)
}
cm := ipv6.ControlMessage{
TrafficClass: 0xc0, // DSCP CS6
HopLimit: 1,
IfIndex: en0.Index,
}
if _, err := p.WriteTo(ospf, &cm, &allSPFRouters); err != nil {
log.Fatal(err)
}
}
package main
import (
"log"
"net"
"golang.org/x/net/ipv6"
)
func main() {
c, err := net.ListenPacket("udp6", "[::]:5353") // mDNS over UDP
if err != nil {
log.Fatal(err)
}
defer c.Close()
p := ipv6.NewPacketConn(c)
en0, err := net.InterfaceByName("en0")
if err != nil {
log.Fatal(err)
}
mDNSLinkLocal := net.UDPAddr{IP: net.ParseIP("ff02::fb")}
if err := p.JoinGroup(en0, &mDNSLinkLocal); err != nil {
log.Fatal(err)
}
defer p.LeaveGroup(en0, &mDNSLinkLocal)
if err := p.SetControlMessage(ipv6.FlagDst|ipv6.FlagInterface, true); err != nil {
log.Fatal(err)
}
var wcm ipv6.ControlMessage
b := make([]byte, 1500)
for {
_, rcm, peer, err := p.ReadFrom(b)
if err != nil {
log.Fatal(err)
}
if !rcm.Dst.IsMulticast() || !rcm.Dst.Equal(mDNSLinkLocal.IP) {
continue
}
wcm.IfIndex = rcm.IfIndex
answers := []byte("FAKE-MDNS-ANSWERS") // fake mDNS answers, you need to implement this
if _, err := p.WriteTo(answers, &wcm, peer); err != nil {
log.Fatal(err)
}
}
}
package main
import (
"fmt"
"log"
"net"
"os"
"time"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv6"
)
func main() {
// Tracing an IP packet route to www.google.com.
const host = "www.google.com"
ips, err := net.LookupIP(host)
if err != nil {
log.Fatal(err)
}
var dst net.IPAddr
for _, ip := range ips {
if ip.To16() != nil && ip.To4() == nil {
dst.IP = ip
fmt.Printf("using %v for tracing an IP packet route to %s\n", dst.IP, host)
break
}
}
if dst.IP == nil {
log.Fatal("no AAAA record found")
}
c, err := net.ListenPacket("ip6:58", "::") // ICMP for IPv6
if err != nil {
log.Fatal(err)
}
defer c.Close()
p := ipv6.NewPacketConn(c)
if err := p.SetControlMessage(ipv6.FlagHopLimit|ipv6.FlagSrc|ipv6.FlagDst|ipv6.FlagInterface, true); err != nil {
log.Fatal(err)
}
wm := icmp.Message{
Type: ipv6.ICMPTypeEchoRequest, Code: 0,
Body: &icmp.Echo{
ID: os.Getpid() & 0xffff,
Data: []byte("HELLO-R-U-THERE"),
},
}
var f ipv6.ICMPFilter
f.SetAll(true)
f.Accept(ipv6.ICMPTypeTimeExceeded)
f.Accept(ipv6.ICMPTypeEchoReply)
if err := p.SetICMPFilter(&f); err != nil {
log.Fatal(err)
}
var wcm ipv6.ControlMessage
rb := make([]byte, 1500)
for i := 1; i <= 64; i++ { // up to 64 hops
wm.Body.(*icmp.Echo).Seq = i
wb, err := wm.Marshal(nil)
if err != nil {
log.Fatal(err)
}
// In the real world usually there are several
// multiple traffic-engineered paths for each hop.
// You may need to probe a few times to each hop.
begin := time.Now()
wcm.HopLimit = i
if _, err := p.WriteTo(wb, &wcm, &dst); err != nil {
log.Fatal(err)
}
if err := p.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil {
log.Fatal(err)
}
n, rcm, peer, err := p.ReadFrom(rb)
if err != nil {
if err, ok := err.(net.Error); ok && err.Timeout() {
fmt.Printf("%v\t*\n", i)
continue
}
log.Fatal(err)
}
rm, err := icmp.ParseMessage(58, rb[:n])
if err != nil {
log.Fatal(err)
}
rtt := time.Since(begin)
// In the real world you need to determine whether the
// received message is yours using ControlMessage.Src,
// ControlMesage.Dst, icmp.Echo.ID and icmp.Echo.Seq.
switch rm.Type {
case ipv6.ICMPTypeTimeExceeded:
names, _ := net.LookupAddr(peer.String())
fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, rcm)
case ipv6.ICMPTypeEchoReply:
names, _ := net.LookupAddr(peer.String())
fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, rcm)
return
}
}
}
Package-Level Type Names (total 8)
/* sort by: | */
A Conn represents a network endpoint that uses IPv6 transport.
It allows to set basic IP-level socket options such as traffic
class and hop limit.genericOpt.Conn*socket.Conn HopLimit returns the hop limit field value for outgoing packets. PathMTU returns a path MTU value for the destination associated
with the endpoint. RecvMsg wraps recvmsg system call.
The provided flags is a set of platform-dependent flags, such as
syscall.MSG_PEEK. RecvMsgs wraps recvmmsg system call.
It returns the number of processed messages.
The provided flags is a set of platform-dependent flags, such as
syscall.MSG_PEEK.
Only Linux supports this. SendMsg wraps sendmsg system call.
The provided flags is a set of platform-dependent flags, such as
syscall.MSG_DONTROUTE. SendMsgs wraps sendmmsg system call.
It returns the number of processed messages.
The provided flags is a set of platform-dependent flags, such as
syscall.MSG_DONTROUTE.
Only Linux supports this. SetHopLimit sets the hop limit field value for future outgoing
packets. SetTrafficClass sets the traffic class field value for future
outgoing packets. TrafficClass returns the traffic class field value for outgoing
packets.
func NewConn(c net.Conn) *Conn
A ControlMessage represents per packet basis IP-level socket
options. // destination address, receiving only // hop limit, must be 1 <= value <= 255 when specifying // interface index, must be 1 <= value when specifying // path MTU, receiving only // next hop address, specifying only // source address, specifying only Receiving socket options: SetControlMessage allows to
receive the options from the protocol stack using ReadFrom
method of PacketConn.
Specifying socket options: ControlMessage for WriteTo
method of PacketConn allows to send the options to the
protocol stack. // traffic class, must be 1 <= value <= 255 when specifying Marshal returns the binary encoding of cm. Parse parses b as a control message and stores the result in cm.(*ControlMessage) String() string
*ControlMessage : expvar.Var
*ControlMessage : fmt.Stringer
A Header represents an IPv6 base header. // destination address // flow label // hop limit // next header // payload length // source address // traffic class // protocol version(*Header) String() string
*Header : expvar.Var
*Header : fmt.Stringer
func ParseHeader(b []byte) (*Header, error)
An ICMPFilter represents an ICMP message filter for incoming
packets. The filter belongs to a packet delivery path on a host and
it cannot interact with forwarding packets or tunnel-outer packets.
Note: RFC 8200 defines a reasonable role model. A node means a
device that implements IP. A router means a node that forwards IP
packets not explicitly addressed to itself, and a host means a node
that is not a router.icmpv6Filter.Data[8]uint32 Accept accepts incoming ICMP packets including the type field value
typ. Block blocks incoming ICMP packets including the type field value
typ. SetAll sets the filter action to the filter. WillBlock reports whether the ICMP type will be blocked.
A Message represents an IO message.
type Message struct {
Buffers [][]byte
OOB []byte
Addr net.Addr
N int
NN int
Flags int
}
The Buffers fields represents a list of contiguous buffers, which
can be used for vectored IO, for example, putting a header and a
payload in each slice.
When writing, the Buffers field must contain at least one byte to
write.
When reading, the Buffers field will always contain a byte to read.
The OOB field contains protocol-specific control or miscellaneous
ancillary data known as out-of-band data.
It can be nil when not required.
The Addr field specifies a destination address when writing.
It can be nil when the underlying protocol of the endpoint uses
connection-oriented communication.
After a successful read, it may contain the source address on the
received packet.
The N field indicates the number of bytes read or written from/to
Buffers.
The NN field indicates the number of bytes read or written from/to
OOB.
The Flags field contains protocol-specific information on the
received message.
A PacketConn represents a packet network endpoint that uses IPv6
transport. It is used to control several IP-level socket options
including IPv6 header manipulation. It also provides datagram
based network I/O methods specific to the IPv6 and higher layer
protocols such as OSPF, GRE, and UDP.payloadHandler.PacketConnnet.PacketConnpayloadHandler.rawOpt.RWMutexsync.RWMutex Checksum reports whether the kernel will compute, store or verify a
checksum for both incoming and outgoing packets. If on is true, it
returns an offset in bytes into the data of where the checksum
field is located. Close closes the endpoint. ExcludeSourceSpecificGroup excludes the source-specific group from
the already joined any-source groups by JoinGroup on the interface
ifi. HopLimit returns the hop limit field value for outgoing packets. ICMPFilter returns an ICMP filter. IncludeSourceSpecificGroup includes the excluded source-specific
group by ExcludeSourceSpecificGroup again on the interface ifi. JoinGroup joins the group address group on the interface ifi.
By default all sources that can cast data to group are accepted.
It's possible to mute and unmute data transmission from a specific
source by using ExcludeSourceSpecificGroup and
IncludeSourceSpecificGroup.
JoinGroup uses the system assigned multicast interface when ifi is
nil, although this is not recommended because the assignment
depends on platforms and sometimes it might require routing
configuration. JoinSourceSpecificGroup joins the source-specific group comprising
group and source on the interface ifi.
JoinSourceSpecificGroup uses the system assigned multicast
interface when ifi is nil, although this is not recommended because
the assignment depends on platforms and sometimes it might require
routing configuration. LeaveGroup leaves the group address group on the interface ifi
regardless of whether the group is any-source group or
source-specific group. LeaveSourceSpecificGroup leaves the source-specific group on the
interface ifi. LocalAddr returns the local network address, if known. Lock locks rw for writing.
If the lock is already locked for reading or writing,
Lock blocks until the lock is available. MulticastHopLimit returns the hop limit field value for outgoing
multicast packets. MulticastInterface returns the default interface for multicast
packet transmissions. MulticastLoopback reports whether transmitted multicast packets
should be copied and send back to the originator. RLock locks rw for reading.
It should not be used for recursive read locking; a blocked Lock
call excludes new readers from acquiring the lock. See the
documentation on the [RWMutex] type. RLocker returns a [Locker] interface that implements
the [Locker.Lock] and [Locker.Unlock] methods by calling rw.RLock and rw.RUnlock. RUnlock undoes a single [RWMutex.RLock] call;
it does not affect other simultaneous readers.
It is a run-time error if rw is not locked for reading
on entry to RUnlock. ReadBatch reads a batch of messages.
The provided flags is a set of platform-dependent flags, such as
syscall.MSG_PEEK.
On a successful read it returns the number of messages received, up
to len(ms).
On Linux, a batch read will be optimized.
On other platforms, this method will read only a single message. ReadFrom reads a payload of the received IPv6 datagram, from the
endpoint c, copying the payload into b. It returns the number of
bytes copied into b, the control message cm and the source address
src of the received datagram. SetBPF attaches a BPF program to the connection.
Only supported on Linux. SetChecksum enables the kernel checksum processing. If on is true,
the offset should be an offset in bytes into the data of where the
checksum field is located. SetControlMessage allows to receive the per packet basis IP-level
socket options. SetDeadline sets the read and write deadlines associated with the
endpoint. SetHopLimit sets the hop limit field value for future outgoing
packets. SetICMPFilter deploys the ICMP filter. SetMulticastHopLimit sets the hop limit field value for future
outgoing multicast packets. SetMulticastInterface sets the default interface for future
multicast packet transmissions. SetMulticastLoopback sets whether transmitted multicast packets
should be copied and send back to the originator. SetReadDeadline sets the read deadline associated with the
endpoint. SetTrafficClass sets the traffic class field value for future
outgoing packets. SetWriteDeadline sets the write deadline associated with the
endpoint. TrafficClass returns the traffic class field value for outgoing
packets. TryLock tries to lock rw for writing and reports whether it succeeded.
Note that while correct uses of TryLock do exist, they are rare,
and use of TryLock is often a sign of a deeper problem
in a particular use of mutexes. TryRLock tries to lock rw for reading and reports whether it succeeded.
Note that while correct uses of TryRLock do exist, they are rare,
and use of TryRLock is often a sign of a deeper problem
in a particular use of mutexes. Unlock unlocks rw for writing. It is a run-time error if rw is
not locked for writing on entry to Unlock.
As with Mutexes, a locked [RWMutex] is not associated with a particular
goroutine. One goroutine may [RWMutex.RLock] ([RWMutex.Lock]) a RWMutex and then
arrange for another goroutine to [RWMutex.RUnlock] ([RWMutex.Unlock]) it. WriteBatch writes a batch of messages.
The provided flags is a set of platform-dependent flags, such as
syscall.MSG_DONTROUTE.
It returns the number of messages written on a successful write.
On Linux, a batch write will be optimized.
On other platforms, this method will write only a single message. WriteTo writes a payload of the IPv6 datagram, to the destination
address dst through the endpoint c, copying the payload from b. It
returns the number of bytes written. The control message cm allows
the IPv6 header fields and the datagram path to be specified. The
cm may be nil if control of the outgoing datagram is not required.
*PacketConn : golang.org/x/net/bpf.Setter
*PacketConn : github.com/pion/datachannel.ReadDeadliner
*PacketConn : github.com/pion/datachannel.WriteDeadliner
*PacketConn : github.com/pion/transport/v2/udp.BatchPacketConn
*PacketConn : github.com/pion/transport/v2/udp.BatchReader
*PacketConn : github.com/pion/transport/v2/udp.BatchWriter
*PacketConn : github.com/prometheus/common/expfmt.Closer
*PacketConn : io.Closer
*PacketConn : sync.Locker
func NewPacketConn(c net.PacketConn) *PacketConn
func github.com/pion/mdns/v2.Server(multicastPktConnV4 *ipv4.PacketConn, multicastPktConnV6 *PacketConn, config *mdns.Config) (*mdns.Conn, error)
Package-Level Functions (total 4)
NewConn returns a new Conn.
NewControlMessage returns a new control message.
The returned message is large enough for options specified by cf.
NewPacketConn returns a new PacketConn using c as its underlying
transport.
ParseHeader parses b as an IPv6 base header.
Package-Level Constants (total 45)
const FlagDstControlFlags = 8 // pass the destination address on the received packet
The pages are generated with Goldsv0.8.2. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.