net Package--Reading Abstracts

Keywords: Go network Unix DNS Mac

brief introduction

In the net package, there are many structures, various functions and methods. I decided to go through it on the whole and make a map.

Copy and paste source: https://studygolang.com/stati...

constant

const (
    IPv4len = 4
    IPv6len = 16
)

global variable

Commonly used IPv4 address.

var (
    IPv4bcast     = IPv4(255, 255, 255, 255) // Broadcast address
    IPv4allsys    = IPv4(224, 0, 0, 1)       // All hosts and routers
    IPv4allrouter = IPv4(224, 0, 0, 2)       // All routers
    IPv4zero      = IPv4(0, 0, 0, 0)         // Local address, only as source address (used as broadcast address)
)

Many OpError-type errors include this error.

var (
    ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection")
)

Error interface

The built-in error means that when dealing with the errors of net packages, we should remember that go net packages have encapsulated such an error interface for us.

type Error interface {
    error            // =>Error()string
    Timeout() bool   // Is the error timed out?
    Temporary() bool // Is the error temporary?
}

Implementation Types of Various Error Interfaces

Through its naming, we can intuitively see what kind of errors they are.

  • UnknownNetworkError
type UnknownNetworkError string
  • InvalidAddrError
type InvalidAddrError string
  • DNSConfigError: DNSConfigError represents an error in reading the host DNS configuration.
type DNSConfigError struct {
    Err error
}

Question: Why does this structure value contain a built-in error interface type? What's the purpose of packaging?

  • DNSError
type DNSError struct {
    Err       string // Wrong Description
    Name      string // Name of query
    Server    string // Servers used
    IsTimeout bool
}
  • AddrError
type AddrError struct {
    Err  string
    Addr string
}
  • OpError (commonly used)

OpError is an error type that is often returned by functions of net packages. It describes the operation, network type and network address of the error.

type OpError struct {
    // Op is an incorrect operation, such as "read" or "write"
    Op  string
    // Net is the network type where the error occurs, such as "tcp" or "udp6"
    Net string
    // Addr is the wrong network address
    Addr Addr
    // Err is an error in operation
    Err error
}

Hardware Addr type

type HardwareAddr []byte

Obviously, it is used to describe the mac address.

  • Function ParseMAC: Resolve hardware address
func ParseMAC(s string) (hw HardwareAddr, err error)
  • Method String
func (a HardwareAddr) String() string

Flags type: attributes of the interface

type Flags uint
const (
    FlagUp           Flags = 1 << iota // Interface in active state
    FlagBroadcast                      // Interface Support Broadcasting
    FlagLoopback                       // The interface is loopback
    FlagPointToPoint                   // Interfaces are point-to-point
    FlagMulticast                      // Interface Support Multicast
)
  • String method
func (f Flags) String() string

Interface Type: Describes Network Card

What we describe is what we output through ifconfig

type Interface struct {
    Index        int          // Index, >= 1 integer
    MTU          int          // Maximum transmission unit
    Name         string       // Interface names, such as "en0", "lo0", "eth0.100"
    HardwareAddr HardwareAddr // Hardware address, IEEE MAC-48, EUI-48 or EUI-64 format
    Flags        Flags        // Interface properties, such as FlagUp, FlagLoopback, FlagMulticast
}
  • InterfaceByIndex function: Returns the network interface of the specified index
func InterfaceByIndex(index int) (*Interface, error)
  • InterfaceByName function: Returns the network interface with the specified name.
func InterfaceByName(name string) (*Interface, error)
  • Interfaces function: Returns the list of network interfaces for the system
func Interfaces() ([]Interface, error)
  • InterfaceAddrs function: Returns the address list of the network interface of the system
func InterfaceAddrs() ([]Addr, error)
  • Addrs method: Returns one or more interface addresses of the network interface ifi
func (ifi *Interface) Addrs() ([]Addr, error)
  • MulticastAddrs method: Returns the multicast group address that the network interface ifi joined.
func (ifi *Interface) MulticastAddrs() ([]Addr, error)

Example:

func main() {

    infslice, _ := net.Interfaces()
    w := new(tabwriter.Writer).Init(os.Stdout, 8, 8, 3, ' ', 0)
    fmt.Fprintln(w, "Index\tName\tMac\tMTU\tFlags\tAddrs")
    for _, inf := range infslice {
        addr, _ := inf.Addrs()
        fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\t%v\n", inf.Index, inf.Name, inf.HardwareAddr, inf.MTU, inf.Flags, addr)
    }
    w.Flush()

}

IP Type: Describes ipv4 or ipv6 addresses

Note: IPV4 or IPV6 cannot be judged by its slice length in development

type IP []byte
  • IPv4 function: Returns the IP address containing an IPv4 address a.b.c.d (in 16 byte format). `
  • ParseIP function: parse s into an IP address and return it. If s is not a legitimate IP address text representation, ParseIP returns nil.
  • DefaultMask method: Returns the default subnet mask of IP address ip. Only IPv4 has a default subnet mask; if IP is not a legitimate IPv4 address, it returns nil.
  • Equal method: If IP and x represent the same IP address, Equal returns true. IPv4 addresses representing the same address and IPv6 addresses are also considered equal.
  • Mask Method: Return Network Number
func IPv4(a, b, c, d byte) IP
func ParseIP(s string) IP
func (ip IP) DefaultMask() IPMask
func (ip IP) Equal(x IP) bool
func (ip IP) Mask(mask IPMask) IP

IPMask Type: Describes IPv4 Address Mask

type IPMask []byte
  • IPv4Mask function: Returns a 4-byte IPv4 mask a.b.c.d.
  • CIDRMask function: Returns an IPMask type value with a total of bits, of which the first one is 1 and the rest are 0.
  • Size method: Returns the leading digits of M and the total digits. If m is not a standard subnet mask (word: /^ 1 + 0 +$/), it will return (0, 0).
func IPv4Mask(a, b, c, d byte) IPMask
func CIDRMask(ones, bits int) IPMask
func (m IPMask) Size() (ones, bits int)

IPNet Type: Represents an IP Network (IP+MASK)

type IPNet struct {
    IP   IP     // network address
    Mask IPMask // Subnet mask
}
  • ParseCIDR function: parse s as an IP address and mask string of CIDR (untyped inter-domain routing), such as "192.168.100.1/24" or "2001:DB8:/48", parse and return IP address and IP network. For "192.168.100.1/24", the IP address 192.168.100.1 and the IP network 192.168.0.0/16 will be returned.
  • Contains function: Report whether the network contains address ip
  • Network method: Returns the name of the network type: "ip+net". In fact, to put it plainly, it returns such a string whatever it is?
func ParseCIDR(s string) (IP, *IPNet, error)
func (n *IPNet) Contains(ip IP) bool
func (n *IPNet) Network() string

Addr interface: represents the terminal address in a network

type Addr interface {
    Network() string // Network name, eg:"tcp“
    String() string  // String format address, eg: "127.0.0.1:10999“
}

Conn Interface: A Universal Flow-Oriented Network Connection

type Conn interface {
    // Read Reads Data from Connections
    // The Read method may overtime an error after exceeding a fixed time limit, and the Timeout() method of the error returns true.
    Read(b []byte) (n int, err error)
    // Write writes data from a connection
    // The Write method may overtime an error after exceeding a fixed time limit, and the Timeout() method of the error returns true.
    Write(b []byte) (n int, err error)
    // Close method closes the connection
    // It also causes Read or Write methods in any blocking to stop blocking and return errors
    Close() error
    // Return to local network address
    LocalAddr() Addr
    // Return to the remote network address
    RemoteAddr() Addr
    // Setting the read-write deadline of the connection is equivalent to calling SetReadDeadline and SetWriteDeadline at the same time.
    // deadline is an absolute time beyond which I/O operations will return directly without blocking due to a timeout failure
    // deadline works for all subsequent I/O operations, not just the next read or write operation
    // The parameter t is zero to denote no deadline
    SetDeadline(t time.Time) error
    // Set the read operation deadline for the connection, and the parameter t is zero to indicate that no deadline is set.
    SetReadDeadline(t time.Time) error
    // Set the deadline for the write operation of the connection, and the parameter t is zero to indicate that no deadline is set.
    // Even if the write timeout occurs, the return value n may be > 0, indicating that some data has been successfully written.
    SetWriteDeadline(t time.Time) error
}
  • Dial function: Connect address on network work and return a Conn interface
  • DialTimeout function: similar to Dial but with timeout. The timeout parameter can include name resolution if necessary.
  • Pipe function: Create a synchronous, full-duplex network connection in memory. Conn interface is implemented at both ends of the connection. Reading at one end corresponds to writing at the other end, which directly copies data between the two ends; there is no internal buffer.
// network:"tcp","tcp4","tcp6","udp","udp4","udp6","ip","ip4","ip6","unix","unixgram","unixpacket"
// Adress supports domain names and provides ports
func Dial(network, address string) (Conn, error)
func DialTimeout(network, address string, timeout time.Duration) (Conn, error)
func Pipe() (Conn, Conn)

PacketConn interface: Represents a generic packet-oriented network connection.

network layer

type PacketConn interface {
    // The ReadFrom method reads a packet from the connection and writes valid information to b
    // The ReadFrom method may overtime an error after exceeding a fixed time limit, and the Timeout() method of the error returns true.
    // Returns the number of bytes written and the source address of the packet
    ReadFrom(b []byte) (n int, addr Addr, err error)
    // WriteTo method writes valid data b to a packet and sends it to addr
    // The WriteTo method may overtime an error after exceeding a fixed time limit, and the Timeout() method of the error returns true.
    // Write timeouts are rare in packet-oriented connections
    WriteTo(b []byte, addr Addr) (n int, err error)
    // Close method closes the connection
    // Causes ReadFrom or WriteTo methods in any blocking to stop blocking and return errors
    Close() error
    // Return to local network address
    LocalAddr() Addr
    // Set the read-write deadline for this connection
    SetDeadline(t time.Time) error
    // Set the read operation deadline for the connection, and the parameter t is zero to indicate that no deadline is set.
    // If the time reaches deadline, the read operation will return without blocking because of a timeout failure.
    SetReadDeadline(t time.Time) error
    // Set the deadline for the write operation of the connection, and the parameter t is zero to indicate that no deadline is set.
    // If the time reaches deadline, the write operation will return directly due to a timeout failure without blocking
    // Even if the write timeout occurs, the return value n may be > 0, indicating that some data has been successfully written.
    SetWriteDeadline(t time.Time) error
}
  • ListenPacket function: listen for the local network address laddr. Network type net must be packet-oriented network type
// net:"ip", "ip4", "ip6", "udp", "udp4", "udp6", or "unixgram"
// The format of laddr is shown in the Dial function.
func ListenPacket(net, laddr string) (PacketConn, error)

IPConn type: Represents IP network connection, implements Conn and PacketetConn interfaces

type IPConn struct {
    // Containing hidden or non-exported fields
}

TCPConn type: Represents a TCP network connection and implements the Conn interface.

type TCPConn struct {
    // Containing hidden or non-exported fields
}

UDPConn type: UDPConn represents a UDP network connection and implements Conn and PacketetConn interfaces.

type UDPConn struct {
    // Containing hidden or non-exported fields
}

UnixConn type: Represents socket connection in Unix domain, implements Conn and PacketConn interfaces

type UnixConn struct {
    // Containing hidden or non-exported fields
}

Dialer Type: Contains parameters when connecting to an address

type Dialer struct {
    // Timeout is the maximum time the dial operation waits for the connection to be established, and the default value represents no timeout.
    // If the Deadline field is also set, the dial operation may fail earlier.
    // Whether or not a timeout is set, the operating system may enforce its timeout settings.
    // For example, TCP (system) timeouts are usually about 3 minutes.
    Timeout time.Duration
    // Deadline is a specific point-in-time deadline beyond which the dial operation will fail.
    // If the Timeout field is also set, the dial operation may fail earlier.
    // Zero means no deadline, i.e. compliance with operating system timeout settings.
    Deadline time.Time
    // LocalAddr is the local address used when dial is an address.
    // The address must be a type compatible with dial's network.
    // If it is nil, a local address will be automatically selected.
    LocalAddr Addr
    // DualStack allows a single dial operation with a network type of "tcp".
    // When the DNS record of the destination is a host name with multiple addresses,
    // Attempt to establish multiple IPv4 and IPv6 connections and return to the first established connection.
    DualStack bool
    // KeepAlive specifies the lifetime of an active network connection; if 0, keep-alive is prohibited.
    // Network connections that do not support keep-alive ignore this field.
    KeepAlive time.Duration
}

The zero value of each field is equivalent to the absence of that field. So calling a Dial method with Dialer zero is equivalent to calling a Dial function.

  • Dial method: Connect the specified address on the specified network. A lot more control information than the Dial function.
func (d *Dialer) Dial(network, address string) (Conn, error)

Listener interface: A common network listener interface for stream-oriented network protocols.

type Listener interface {
    // Addr returns the network address of the interface
    Addr() Addr
    // Accept waits and returns the next connection to the interface
    Accept() (c Conn, err error)
    // Close closes the interface and makes any blocked Accept operation stop blocking and return an error.
    Close() error
}
  • Listen function: Returns a Listener listened on a local network address laddr. Network type parameter net must be a flow-oriented network
func Listen(net, laddr string) (Listener, error)

TCPListener type

TCPListener represents the listener of a TCP network. Users should try to use the Listener interface instead of assuming (network connection is) TCP.

type TCPListener struct {
    // Containing hidden or non-exported fields
}

UnixListener type

UnixListener represents a listener for a Unix domain scoket. Users should try to use the Listener interface instead of assuming that the Unix domain Scoket is connected to the network.

type UnixListener struct {
    // Containing hidden or non-exported fields
}

IPAddr

type IPAddr struct {
    IP   IP
    Zone string // IPv6 Range Address Domain
}
  • ResolveIPAddr function: Resolve addr as an IP address in the form of "host" or "ipv6-host%zone". The function parses on the network type specified by the parameter net, which must be "ip", "ip4" or "ip6".
  • Network method: Return the network type of address: "ip".
func ResolveIPAddr(net, addr string) (*IPAddr, error)
func (a *IPAddr) Network() string

TCPAddr Type: Represents a TCP Terminal Address

type TCPAddr struct {
    IP   IP
    Port int
    Zone string // IPv6 Range Address Domain
}
  • ResolveTCPAddr function: Resolve and return addr as TCP address. The parameter addr format is "host:port" or "[ipv6-host%zone]:port", and the network name and port name can be parsed; net must be "tcp", "tcp4" or "tcp6".
  • Network method: "tcp"

UDPAddr type: Represents a UDP terminal address

type UDPAddr struct {
    IP   IP
    Port int
    Zone string // IPv6 Range Address Domain
}
  • ResolveTCPAddr function: Resolve and return addr as TCP address. The parameter addr format is "host:port" or "[ipv6-host%zone]:port", and the network name and port name can be parsed; net must be "udp", "udp4" or "udp6".
  • Network method: Returns the network type of address, "udp".

UnixAddr Type: Represents a Unix domain socket terminal address

Posted by notsleepy on Mon, 12 Aug 2019 05:30:27 -0700