Back to godoc.org

Package ipv4

v0.2.0
Latest Go to latest

The latest major version is .

Published: Dec 23, 2013 | Licenses: Apache-2.0 , BSD-3-Clause | Module: go.etcd.io/etcd

Overview

Package ipv4 implements IP-level socket options for the Internet Protocol version 4.

The package provides IP-level socket options that allow manipulation of IPv4 facilities. The IPv4 and basic host requirements for IPv4 are defined in RFC 791, RFC 1112 and RFC 1122.

Unicasting

The options for unicasting are available for net.TCPConn, net.UDPConn and net.IPConn which are created as network connections that use the IPv4 transport. When a single TCP connection carrying a data flow of multiple packets needs to indicate the flow is important, ipv4.Conn is used to set the type-of-service field on the IPv4 header for each packet.

ln, err := net.Listen("tcp4", "0.0.0.0: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, as known as AF11 packets.

		if err := ipv4.NewConn(c).SetTOS(DiffServAF11); 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 IPv4 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.IPv4(224, 0, 0, 250)

First, an application listens to an appropriate address with an appropriate service port.

c, err := net.ListenPacket("udp4", "0.0.0.0: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 IPv4 and Ethernet.

p := ipv4.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 ipv4.PacketConn is used to enable control message transmissons.

if err := p.SetControlMessage(ipv4.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, cm, src, err := p.ReadFrom(b)
	if err != nil {
		// error handling
	}
	if cm.Dst.IsMulticast() {
		if cm.Dst.Equal(group)
			// joined group, do something
		} else {
			// unknown group, discard
			continue
		}
	}

The application can also send both unicast and multicast packets.

	p.SetTOS(DiffServCS0)
	p.SetTTL(16)
	if _, err := p.WriteTo(data, nil, src); err != nil {
		// error handling
	}
	dst := &net.UDPAddr{IP: group, Port: 1024}
	for _, ifi := range []*net.Interface{en0, en1} {
		if err := p.SetMulticastInterface(ifi); err != nil {
			// error handling
		}
		p.SetMulticastTTL(2)
		if _, err := p.WriteTo(data, nil, dst); err != nil {
			// error handling
		}
	}
}

More multicasting

An application that uses PacketConn or RawConn 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("udp4", "0.0.0.0:1024")
if err != nil {
	// error handling
}
defer c.Close()
p := ipv4.NewPacketConn(c)
if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 248)}); err != nil {
	// error handling
}
if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 249)}); err != nil {
	// error handling
}
if err := p.JoinGroup(en1, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 249)}); 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("udp4", "224.0.0.0:1024")
if err != nil {
	// error handling
}
defer c1.Close()
c2, err := net.ListenPacket("udp4", "224.0.0.0:1024")
if err != nil {
	// error handling
}
defer c2.Close()
p1 := ipv4.NewPacketConn(c1)
if err := p1.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 248)}); err != nil {
	// error handling
}
p2 := ipv4.NewPacketConn(c2)
if err := p2.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 248)}); 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.IPv4(224, 0, 0, 248)}); err != nil {
	// error handling
}
if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 250)}); err != nil {
	// error handling
}

Index

Constants

const (
	Version   = 4  // protocol version
	HeaderLen = 20 // header length without extension headers

)

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

A Conn represents a network endpoint that uses the IPv4 transport. It is used to control basic IP-level socket options such as TOS and TTL.

func NewConn

func NewConn(c net.Conn) *Conn

NewConn returns a new Conn.

func (*Conn) SetTOS

func (c *Conn) SetTOS(tos int) error

SetTOS sets the type-of-service field value for future outgoing packets.

func (*Conn) SetTTL

func (c *Conn) SetTTL(ttl int) error

SetTTL sets the time-to-live field value for future outgoing packets.

func (*Conn) TOS

func (c *Conn) TOS() (int, error)

TOS returns the type-of-service field value for outgoing packets.

func (*Conn) TTL

func (c *Conn) TTL() (int, error)

TTL returns the time-to-live field value for outgoing packets.

type ControlFlags

type ControlFlags uint
const (
	FlagTTL       ControlFlags = 1 << iota // pass the TTL on the received packet
	FlagSrc                                // pass the source address on the received packet
	FlagDst                                // pass the destination address on the received packet
	FlagInterface                          // pass the interface index on the received packet
)

type ControlMessage

type ControlMessage struct {
	// Receiving socket options: SetControlMessage allows to
	// receive the options from the protocol stack using ReadFrom
	// method of PacketConn or RawConn.
	//
	// Specifying socket options: ControlMessage for WriteTo
	// method of PacketConn or RawConn allows to send the options
	// to the protocol stack.
	//
	TTL     int    // time-to-live, receiving only
	Src     net.IP // source address, specifying only
	Dst     net.IP // destination address, receiving only
	IfIndex int    // interface index, must be 1 <= value when specifying
}

A ControlMessage represents per packet basis IP-level socket options.

func (*ControlMessage) String

func (cm *ControlMessage) String() string
type Header struct {
	Version  int         // protocol version
	Len      int         // header length
	TOS      int         // type-of-service
	TotalLen int         // packet total length
	ID       int         // identification
	Flags    HeaderFlags // flags
	FragOff  int         // fragment offset
	TTL      int         // time-to-live
	Protocol int         // next protocol
	Checksum int         // checksum
	Src      net.IP      // source address
	Dst      net.IP      // destination address
	Options  []byte      // options, extension headers
}

A Header represents an IPv4 header.

func ParseHeader

func ParseHeader(b []byte) (*Header, error)

ParseHeader parses b as an IPv4 header.

func (*Header) Marshal

func (h *Header) Marshal() ([]byte, error)

Marshal returns the binary encoding of the IPv4 header h.

func (*Header) String

func (h *Header) String() string

type HeaderFlags

type HeaderFlags int
const (
	MoreFragments HeaderFlags = 1 << iota // more fragments flag
	DontFragment                          // don't fragment flag
)

type ICMPType

type ICMPType int

An ICMPType represents a type of ICMP message.

const (
	ICMPTypeEchoReply              ICMPType = 0  // Echo Reply
	ICMPTypeDestinationUnreachable ICMPType = 3  // Destination Unreachable
	ICMPTypeRedirect               ICMPType = 5  // Redirect
	ICMPTypeEcho                   ICMPType = 8  // Echo
	ICMPTypeRouterAdvertisement    ICMPType = 9  // Router Advertisement
	ICMPTypeRouterSolicitation     ICMPType = 10 // Router Solicitation
	ICMPTypeTimeExceeded           ICMPType = 11 // Time Exceeded
	ICMPTypeParameterProblem       ICMPType = 12 // Parameter Problem
	ICMPTypeTimestamp              ICMPType = 13 // Timestamp
	ICMPTypeTimestampReply         ICMPType = 14 // Timestamp Reply
	ICMPTypePhoturis               ICMPType = 40 // Photuris
)

Internet Control Message Protocol (ICMP) Parameters, Updated: 2013-04-19

func (ICMPType) String

func (typ ICMPType) String() string

type PacketConn

type PacketConn struct {
	// contains filtered or unexported fields
}

A PacketConn represents a packet network endpoint that uses the IPv4 transport. It is used to control several IP-level socket options including multicasting. It also provides datagram based network I/O methods specific to the IPv4 and higher layer protocols such as UDP.

func NewPacketConn

func NewPacketConn(c net.PacketConn) *PacketConn

NewPacketConn returns a new PacketConn using c as its underlying transport.

func (*PacketConn) Close

func (c *PacketConn) Close() error

Close closes the endpoint.

func (*PacketConn) JoinGroup

func (c *PacketConn) JoinGroup(ifi *net.Interface, group net.Addr) error

JoinGroup joins the group address group on the interface ifi. It 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.

func (*PacketConn) LeaveGroup

func (c *PacketConn) LeaveGroup(ifi *net.Interface, group net.Addr) error

LeaveGroup leaves the group address group on the interface ifi.

func (*PacketConn) MulticastInterface

func (c *PacketConn) MulticastInterface() (*net.Interface, error)

MulticastInterface returns the default interface for multicast packet transmissions.

func (*PacketConn) MulticastLoopback

func (c *PacketConn) MulticastLoopback() (bool, error)

MulticastLoopback reports whether transmitted multicast packets should be copied and send back to the originator.

func (*PacketConn) MulticastTTL

func (c *PacketConn) MulticastTTL() (int, error)

MulticastTTL returns the time-to-live field value for outgoing multicast packets.

func (*PacketConn) ReadFrom

func (c *PacketConn) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error)

ReadFrom reads a payload of the received IPv4 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.

func (*PacketConn) SetControlMessage

func (c *PacketConn) SetControlMessage(cf ControlFlags, on bool) error

SetControlMessage sets the per packet IP-level socket options.

func (*PacketConn) SetDeadline

func (c *PacketConn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the endpoint.

func (*PacketConn) SetMulticastInterface

func (c *PacketConn) SetMulticastInterface(ifi *net.Interface) error

SetMulticastInterface sets the default interface for future multicast packet transmissions.

func (*PacketConn) SetMulticastLoopback

func (c *PacketConn) SetMulticastLoopback(on bool) error

SetMulticastLoopback sets whether transmitted multicast packets should be copied and send back to the originator.

func (*PacketConn) SetMulticastTTL

func (c *PacketConn) SetMulticastTTL(ttl int) error

SetMulticastTTL sets the time-to-live field value for future outgoing multicast packets.

func (*PacketConn) SetReadDeadline

func (c *PacketConn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline associated with the endpoint.

func (*PacketConn) SetTOS

func (c *PacketConn) SetTOS(tos int) error

SetTOS sets the type-of-service field value for future outgoing packets.

func (*PacketConn) SetTTL

func (c *PacketConn) SetTTL(ttl int) error

SetTTL sets the time-to-live field value for future outgoing packets.

func (*PacketConn) SetWriteDeadline

func (c *PacketConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline associated with the endpoint.

func (*PacketConn) TOS

func (c *PacketConn) TOS() (int, error)

TOS returns the type-of-service field value for outgoing packets.

func (*PacketConn) TTL

func (c *PacketConn) TTL() (int, error)

TTL returns the time-to-live field value for outgoing packets.

func (*PacketConn) WriteTo

func (c *PacketConn) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error)

WriteTo writes a payload of the IPv4 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 datagram path and the outgoing interface to be specified. Currently only Linux supports this. The cm may be nil if control of the outgoing datagram is not required.

type RawConn

type RawConn struct {
	// contains filtered or unexported fields
}

A RawConn represents a packet network endpoint that uses the IPv4 transport. It is used to control several IP-level socket options including IPv4 header manipulation. It also provides datagram based network I/O methods specific to the IPv4 and higher layer protocols that handle IPv4 datagram directly such as OSPF, GRE.

func NewRawConn

func NewRawConn(c net.PacketConn) (*RawConn, error)

NewRawConn returns a new RawConn using c as its underlying transport.

func (*RawConn) Close

func (c *RawConn) Close() error

Close closes the endpoint.

func (*RawConn) JoinGroup

func (c *RawConn) JoinGroup(ifi *net.Interface, group net.Addr) error

JoinGroup joins the group address group on the interface ifi. It 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.

func (*RawConn) LeaveGroup

func (c *RawConn) LeaveGroup(ifi *net.Interface, group net.Addr) error

LeaveGroup leaves the group address group on the interface ifi.

func (*RawConn) MulticastInterface

func (c *RawConn) MulticastInterface() (*net.Interface, error)

MulticastInterface returns the default interface for multicast packet transmissions.

func (*RawConn) MulticastLoopback

func (c *RawConn) MulticastLoopback() (bool, error)

MulticastLoopback reports whether transmitted multicast packets should be copied and send back to the originator.

func (*RawConn) MulticastTTL

func (c *RawConn) MulticastTTL() (int, error)

MulticastTTL returns the time-to-live field value for outgoing multicast packets.

func (*RawConn) ReadFrom

func (c *RawConn) ReadFrom(b []byte) (h *Header, p []byte, cm *ControlMessage, err error)

ReadFrom reads an IPv4 datagram from the endpoint c, copying the datagram into b. It returns the received datagram as the IPv4 header h, the payload p and the control message cm.

func (*RawConn) SetControlMessage

func (c *RawConn) SetControlMessage(cf ControlFlags, on bool) error

SetControlMessage sets the per packet IP-level socket options.

func (*RawConn) SetDeadline

func (c *RawConn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the endpoint.

func (*RawConn) SetMulticastInterface

func (c *RawConn) SetMulticastInterface(ifi *net.Interface) error

SetMulticastInterface sets the default interface for future multicast packet transmissions.

func (*RawConn) SetMulticastLoopback

func (c *RawConn) SetMulticastLoopback(on bool) error

SetMulticastLoopback sets whether transmitted multicast packets should be copied and send back to the originator.

func (*RawConn) SetMulticastTTL

func (c *RawConn) SetMulticastTTL(ttl int) error

SetMulticastTTL sets the time-to-live field value for future outgoing multicast packets.

func (*RawConn) SetReadDeadline

func (c *RawConn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline associated with the endpoint.

func (*RawConn) SetTOS

func (c *RawConn) SetTOS(tos int) error

SetTOS sets the type-of-service field value for future outgoing packets.

func (*RawConn) SetTTL

func (c *RawConn) SetTTL(ttl int) error

SetTTL sets the time-to-live field value for future outgoing packets.

func (*RawConn) SetWriteDeadline

func (c *RawConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline associated with the endpoint.

func (*RawConn) TOS

func (c *RawConn) TOS() (int, error)

TOS returns the type-of-service field value for outgoing packets.

func (*RawConn) TTL

func (c *RawConn) TTL() (int, error)

TTL returns the time-to-live field value for outgoing packets.

func (*RawConn) WriteTo

func (c *RawConn) WriteTo(h *Header, p []byte, cm *ControlMessage) error

WriteTo writes an IPv4 datagram through the endpoint c, copying the datagram from the IPv4 header h and the payload p. The control message cm allows the datagram path and the outgoing interface to be specified. Currently only Linux supports this. The cm may be nil if control of the outgoing datagram is not required.

The IPv4 header h must contain appropriate fields that include:

Version       = ipv4.Version
Len           = <must be specified>
TOS           = <must be specified>
TotalLen      = <must be specified>
ID            = platform sets an appropriate value if ID is zero
FragOff       = <must be specified>
TTL           = <must be specified>
Protocol      = <must be specified>
Checksum      = platform sets an appropriate value if Checksum is zero
Src           = platform sets an appropriate value if Src is nil
Dst           = <must be specified>
Options       = optional

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier