net

package module
v0.0.0-...-d9132d2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 13, 2024 License: BSD-2-Clause Imports: 12 Imported by: 0

README

net

This is a port of Go's "net" package. The port offers a subset of Go's "net" package. The subset maintains Go 1 compatiblity guarantee.

The "net" package is modified to use netdev, TinyGo's network device driver interface. Netdev replaces the OS syscall interface for I/O access to the networking device. See drivers/netdev for more information on netdev.

Table of Contents

Using "net" and "net/http" Packages

See README-net.md in drivers repo to more details on using "net" and "net/http" packages in a TinyGo application.

"net" Package

The "net" package is ported from Go 1.21.4. The tree listings below shows the files copied. If the file is marked with an '*', it is copied and modified to work with netdev. If the file is marked with an '+', the file is new. If there is no mark, it is a straight copy.

src/net
├── dial.go			*
├── http
│   ├── client.go		*
│   ├── clone.go
│   ├── cookie.go
│   ├── fs.go
│   ├── header.go		*
│   ├── http.go
│   ├── internal
│   │   ├── ascii
│   │   │   ├── print.go
│   │   │   └── print_test.go
│   │   ├── chunked.go
│   │   └── chunked_test.go
│   ├── jar.go
│   ├── method.go
│   ├── request.go		*
│   ├── response.go		*
│   ├── server.go		*
│   ├── sniff.go
│   ├── status.go
│   ├── transfer.go		*
│   └── transport.go		*
├── interface.go		*
├── ip.go
├── iprawsock.go		*
├── ipsock.go			*
├── lookup.go			*
├── mac.go
├── mac_test.go
├── netdev.go			+
├── net.go			*
├── parse.go
├── pipe.go
├── README.md
├── tcpsock.go			*
├── tlssock.go			+
├── udpsock.go			*
└── unixsock.go			*

src/crypto/tls/
├── common.go			*
├── ticket.go			*
└── tls.go			*

The modifications to "net" are to basically wrap TCPConn, UDPConn, and TLSConn around netdev socket calls. In Go, these net.Conns call out to OS syscalls for the socket operations. In TinyGo, the OS syscalls aren't available, so netdev socket calls are substituted.

The modifications to "net/http" are on the client and the server side. On the client side, the TinyGo code changes remove the back-end round-tripper code and replaces it with direct calls to TCPConns/TLSConns. All of Go's http request/response handling code is intact and operational in TinyGo. Same holds true for the server side. The server side supports the normal server features like ServeMux and Hijacker (for websockets).

Maintaining "net"

As Go progresses, changes to the "net" package need to be periodically back-ported to TinyGo's "net" package. This is to pick up any upstream bug fixes or security fixes.

Changes "net" package files are marked with // TINYGO comments.

The files that are marked modified * may contain only a subset of the original file. Basically only the parts necessary to compile and run the example/net examples are copied (and maybe modified).

Upgrade Steps

Let's define some versions:

MIN = TinyGo minimum Go version supported (e.g. 1.15) CUR = TinyGo "net" current version (e.g. 1.20.5) UPSTREAM = Latest upstream Go version to upgrade to (e.g. 1.21) NEW = TinyGo "net" new version, after upgrade

In example, we'll upgrade from CUR (1.20.5) to UPSTREAM (1.21).

These are the steps to promote TinyGos "net" to latest Go upstream version. These steps should be done when:

  • MIN moved forward
  • TinyGo major release
  • TinyGo minor release to pick up security fixes in UPSTREAM

Step 1:

Backport differences from Go UPSTREAM to Go CUR. Since TinyGo CUR isn't the full Go "net" implementation, only backport differences, don't add new stuff from UPSTREAM (unless it's needed in the NEW release).

NEW = CUR + diff(CUR, UPSTREAM)

If NEW contains updates not compatible with MIN, then NEW will need to revert just those updates back to the CUR version, and annotate with a TINYGO comment. If MIN moves forord, NEW can pull in the UPSTREAM changes.

Step 2:

As a double check, compare NEW against UPSTREAM. The only differences at this point should be excluded (not ported) code from UPSTREAM that wasn't in CUR in the first place, and differences due to changes held back for MIN support.

Step 3:

Test NEW against example/net examples. If everything checks out, then CUR becomes NEW, and we can push to TinyGo.

CUR = NEW

Documentation

Index

Constants

View Source
const (
	IPv4len = 4
	IPv6len = 16
)

IP address lengths (bytes).

Variables

View Source
var (
	IPv4bcast     = IPv4(255, 255, 255, 255) // limited broadcast
	IPv4allsys    = IPv4(224, 0, 0, 1)       // all systems
	IPv4allrouter = IPv4(224, 0, 0, 2)       // all routers
	IPv4zero      = IPv4(0, 0, 0, 0)         // all zeros
)

Well-known IPv4 addresses

View Source
var (
	IPv6zero                   = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
	IPv6unspecified            = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
	IPv6loopback               = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
	IPv6interfacelocalallnodes = IP{0xff, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
	IPv6linklocalallnodes      = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
	IPv6linklocalallrouters    = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02}
)

Well-known IPv6 addresses

View Source
var ErrClosed error = errClosed

ErrClosed is the error returned by an I/O call on a network connection that has already been closed, or that is closed by another goroutine before the I/O is completed. This may be wrapped in another error, and should normally be tested using errors.Is(err, net.ErrClosed).

Functions

func JoinHostPort

func JoinHostPort(host, port string) string

JoinHostPort combines host and port into a network address of the form "host:port". If host contains a colon, as found in literal IPv6 addresses, then JoinHostPort returns "[host]:port".

See func Dial for a description of the host and port parameters.

func LookupPort

func LookupPort(network, service string) (port int, err error)

LookupPort looks up the port for the given network and service.

LookupPort uses context.Background internally; to specify the context, use Resolver.LookupPort.

func ParseCIDR

func ParseCIDR(s string) (IP, *IPNet, error)

ParseCIDR parses s as a CIDR notation IP address and prefix length, like "192.0.2.0/24" or "2001:db8::/32", as defined in RFC 4632 and RFC 4291.

It returns the IP address and the network implied by the IP and prefix length. For example, ParseCIDR("192.0.2.1/24") returns the IP address 192.0.2.1 and the network 192.0.2.0/24.

func Pipe

func Pipe() (Conn, Conn)

Pipe creates a synchronous, in-memory, full duplex network connection; both ends implement the Conn interface. Reads on one end are matched with writes on the other, copying data directly between the two; there is no internal buffering.

func SplitHostPort

func SplitHostPort(hostport string) (host, port string, err error)

SplitHostPort splits a network address of the form "host:port", "host%zone:port", "[host]:port" or "[host%zone]:port" into host or host%zone and port.

A literal IPv6 address in hostport must be enclosed in square brackets, as in "[::1]:80", "[::1%lo0]:80".

See func Dial for a description of the hostport parameter, and host and port results.

Types

type Addr

type Addr interface {
	Network() string // name of the network (for example, "tcp", "udp")
	String() string  // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80")
}

Addr represents a network end point address.

The two methods Network and String conventionally return strings that can be passed as the arguments to Dial, but the exact form and meaning of the strings is up to the implementation.

func InterfaceAddrs

func InterfaceAddrs() ([]Addr, error)

InterfaceAddrs returns a list of the system's unicast interface addresses.

The returned list does not identify the associated interface; use Interfaces and Interface.Addrs for more detail.

type AddrError

type AddrError struct {
	Err  string
	Addr string
}

func (*AddrError) Error

func (e *AddrError) Error() string

type Buffers

type Buffers [][]byte

Buffers contains zero or more runs of bytes to write.

On certain machines, for certain types of connections, this is optimized into an OS-specific batch write operation (such as "writev").

func (*Buffers) Read

func (v *Buffers) Read(p []byte) (n int, err error)

Read from the buffers.

Read implements io.Reader for Buffers.

Read modifies the slice v as well as v[i] for 0 <= i < len(v), but does not modify v[i][j] for any i, j.

func (*Buffers) WriteTo

func (v *Buffers) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes contents of the buffers to w.

WriteTo implements io.WriterTo for Buffers.

WriteTo modifies the slice v as well as v[i] for 0 <= i < len(v), but does not modify v[i][j] for any i, j.

type Conn

type Conn interface {
	// Read reads data from the connection.
	// Read can be made to time out and return an error after a fixed
	// time limit; see SetDeadline and SetReadDeadline.
	Read(b []byte) (n int, err error)

	// Write writes data to the connection.
	// Write can be made to time out and return an error after a fixed
	// time limit; see SetDeadline and SetWriteDeadline.
	Write(b []byte) (n int, err error)

	// Close closes the connection.
	// Any blocked Read or Write operations will be unblocked and return errors.
	Close() error

	// LocalAddr returns the local network address, if known.
	LocalAddr() Addr

	// RemoteAddr returns the remote network address, if known.
	RemoteAddr() Addr

	// SetDeadline sets the read and write deadlines associated
	// with the connection. It is equivalent to calling both
	// SetReadDeadline and SetWriteDeadline.
	//
	// A deadline is an absolute time after which I/O operations
	// fail instead of blocking. The deadline applies to all future
	// and pending I/O, not just the immediately following call to
	// Read or Write. After a deadline has been exceeded, the
	// connection can be refreshed by setting a deadline in the future.
	//
	// If the deadline is exceeded a call to Read or Write or to other
	// I/O methods will return an error that wraps os.ErrDeadlineExceeded.
	// This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
	// The error's Timeout method will return true, but note that there
	// are other possible errors for which the Timeout method will
	// return true even if the deadline has not been exceeded.
	//
	// An idle timeout can be implemented by repeatedly extending
	// the deadline after successful Read or Write calls.
	//
	// A zero value for t means I/O operations will not time out.
	SetDeadline(t time.Time) error

	// SetReadDeadline sets the deadline for future Read calls
	// and any currently-blocked Read call.
	// A zero value for t means Read will not time out.
	SetReadDeadline(t time.Time) error

	// SetWriteDeadline sets the deadline for future Write calls
	// and any currently-blocked Write call.
	// Even if write times out, it may return n > 0, indicating that
	// some of the data was successfully written.
	// A zero value for t means Write will not time out.
	SetWriteDeadline(t time.Time) error
}

Conn is a generic stream-oriented network connection.

Multiple goroutines may invoke methods on a Conn simultaneously.

func Dial

func Dial(network, address string) (Conn, error)

Dial connects to the address on the named network.

See Go "net" package Dial() for more information.

Note: Tinygo Dial supports a subset of networks supported by Go Dial, specifically: "tcp", "tcp4", "udp", and "udp4". IP and unix networks are not supported.

func DialTimeout

func DialTimeout(network, address string, timeout time.Duration) (Conn, error)

DialTimeout acts like Dial but takes a timeout.

The timeout includes name resolution, if required. When using TCP, and the host in the address parameter resolves to multiple IP addresses, the timeout is spread over each consecutive dial, such that each is given an appropriate fraction of the time to connect.

See func Dial for a description of the network and address parameters.

type Dialer

type Dialer struct {
	// Timeout is the maximum amount of time a dial will wait for
	// a connect to complete. If Deadline is also set, it may fail
	// earlier.
	//
	// The default is no timeout.
	//
	// When using TCP and dialing a host name with multiple IP
	// addresses, the timeout may be divided between them.
	//
	// With or without a timeout, the operating system may impose
	// its own earlier timeout. For instance, TCP timeouts are
	// often around 3 minutes.
	Timeout time.Duration

	// Deadline is the absolute point in time after which dials
	// will fail. If Timeout is set, it may fail earlier.
	// Zero means no deadline, or dependent on the operating system
	// as with the Timeout option.
	Deadline time.Time

	// LocalAddr is the local address to use when dialing an
	// address. The address must be of a compatible type for the
	// network being dialed.
	// If nil, a local address is automatically chosen.
	LocalAddr Addr

	// KeepAlive specifies the interval between keep-alive
	// probes for an active network connection.
	// If zero, keep-alive probes are sent with a default value
	// (currently 15 seconds), if supported by the protocol and operating
	// system. Network protocols or operating systems that do
	// not support keep-alives ignore this field.
	// If negative, keep-alive probes are disabled.
	KeepAlive time.Duration
}

A Dialer contains options for connecting to an address.

The zero value for each field is equivalent to dialing without that option. Dialing with the zero value of Dialer is therefore equivalent to just calling the Dial function.

It is safe to call Dialer's methods concurrently.

func (*Dialer) Dial

func (d *Dialer) Dial(network, address string) (Conn, error)

Dial connects to the address on the named network.

See func Dial for a description of the network and address parameters.

Dial uses context.Background internally; to specify the context, use DialContext.

func (*Dialer) DialContext

func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error)

DialContext connects to the address on the named network using the provided context.

The provided Context must be non-nil. If the context expires before the connection is complete, an error is returned. Once successfully connected, any expiration of the context will not affect the connection.

When using TCP, and the host in the address parameter resolves to multiple network addresses, any dial timeout (from d.Timeout or ctx) is spread over each consecutive dial, such that each is given an appropriate fraction of the time to connect. For example, if a host has 4 IP addresses and the timeout is 1 minute, the connect to each single address will be given 15 seconds to complete before trying the next one.

See func Dial for a description of the network and address parameters.

type Error

type Error interface {
	error
	Timeout() bool // Is the error a timeout?

	// Deprecated: Temporary errors are not well-defined.
	// Most "temporary" errors are timeouts, and the few exceptions are surprising.
	// Do not use this method.
	Temporary() bool
}

An Error represents a network error.

type Flags

type Flags uint
const (
	FlagUp           Flags = 1 << iota // interface is administratively up
	FlagBroadcast                      // interface supports broadcast access capability
	FlagLoopback                       // interface is a loopback interface
	FlagPointToPoint                   // interface belongs to a point-to-point link
	FlagMulticast                      // interface supports multicast access capability
	FlagRunning                        // interface is in running state
)

func (Flags) String

func (f Flags) String() string

type HardwareAddr

type HardwareAddr []byte

A HardwareAddr represents a physical hardware address.

func ParseMAC

func ParseMAC(s string) (hw HardwareAddr, err error)

ParseMAC parses s as an IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet IP over InfiniBand link-layer address using one of the following formats:

00:00:5e:00:53:01
02:00:5e:10:00:00:00:01
00:00:00:00:fe:80:00:00:00:00:00:00:02:00:5e:10:00:00:00:01
00-00-5e-00-53-01
02-00-5e-10-00-00-00-01
00-00-00-00-fe-80-00-00-00-00-00-00-02-00-5e-10-00-00-00-01
0000.5e00.5301
0200.5e10.0000.0001
0000.0000.fe80.0000.0000.0000.0200.5e10.0000.0001

func (HardwareAddr) String

func (a HardwareAddr) String() string

type IP

type IP []byte

An IP is a single IP address, a slice of bytes. Functions in this package accept either 4-byte (IPv4) or 16-byte (IPv6) slices as input.

Note that in this documentation, referring to an IP address as an IPv4 address or an IPv6 address is a semantic property of the address, not just the length of the byte slice: a 16-byte slice can still be an IPv4 address.

func IPv4

func IPv4(a, b, c, d byte) IP

IPv4 returns the IP address (in 16-byte form) of the IPv4 address a.b.c.d.

func ParseIP

func ParseIP(s string) IP

ParseIP parses s as an IP address, returning the result. The string s can be in IPv4 dotted decimal ("192.0.2.1"), IPv6 ("2001:db8::68"), or IPv4-mapped IPv6 ("::ffff:192.0.2.1") form. If s is not a valid textual representation of an IP address, ParseIP returns nil.

func (IP) DefaultMask

func (ip IP) DefaultMask() IPMask

DefaultMask returns the default IP mask for the IP address ip. Only IPv4 addresses have default masks; DefaultMask returns nil if ip is not a valid IPv4 address.

func (IP) Equal

func (ip IP) Equal(x IP) bool

Equal reports whether ip and x are the same IP address. An IPv4 address and that same address in IPv6 form are considered to be equal.

func (IP) IsGlobalUnicast

func (ip IP) IsGlobalUnicast() bool

IsGlobalUnicast reports whether ip is a global unicast address.

The identification of global unicast addresses uses address type identification as defined in RFC 1122, RFC 4632 and RFC 4291 with the exception of IPv4 directed broadcast addresses. It returns true even if ip is in IPv4 private address space or local IPv6 unicast address space.

func (IP) IsInterfaceLocalMulticast

func (ip IP) IsInterfaceLocalMulticast() bool

IsInterfaceLocalMulticast reports whether ip is an interface-local multicast address.

func (IP) IsLinkLocalMulticast

func (ip IP) IsLinkLocalMulticast() bool

IsLinkLocalMulticast reports whether ip is a link-local multicast address.

func (IP) IsLinkLocalUnicast

func (ip IP) IsLinkLocalUnicast() bool

IsLinkLocalUnicast reports whether ip is a link-local unicast address.

func (IP) IsLoopback

func (ip IP) IsLoopback() bool

IsLoopback reports whether ip is a loopback address.

func (IP) IsMulticast

func (ip IP) IsMulticast() bool

IsMulticast reports whether ip is a multicast address.

func (IP) IsPrivate

func (ip IP) IsPrivate() bool

IsPrivate reports whether ip is a private address, according to RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses).

func (IP) IsUnspecified

func (ip IP) IsUnspecified() bool

IsUnspecified reports whether ip is an unspecified address, either the IPv4 address "0.0.0.0" or the IPv6 address "::".

func (IP) MarshalText

func (ip IP) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The encoding is the same as returned by String, with one exception: When len(ip) is zero, it returns an empty slice.

func (IP) Mask

func (ip IP) Mask(mask IPMask) IP

Mask returns the result of masking the IP address ip with mask.

func (IP) String

func (ip IP) String() string

String returns the string form of the IP address ip. It returns one of 4 forms:

  • "<nil>", if ip has length 0
  • dotted decimal ("192.0.2.1"), if ip is an IPv4 or IP4-mapped IPv6 address
  • IPv6 conforming to RFC 5952 ("2001:db8::1"), if ip is a valid IPv6 address
  • the hexadecimal form of ip, without punctuation, if no other cases apply

func (IP) To16

func (ip IP) To16() IP

To16 converts the IP address ip to a 16-byte representation. If ip is not an IP address (it is the wrong length), To16 returns nil.

func (IP) To4

func (ip IP) To4() IP

To4 converts the IPv4 address ip to a 4-byte representation. If ip is not an IPv4 address, To4 returns nil.

func (*IP) UnmarshalText

func (ip *IP) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The IP address is expected in a form accepted by ParseIP.

type IPAddr

type IPAddr struct {
	IP   IP
	Zone string // IPv6 scoped addressing zone
}

IPAddr represents the address of an IP end point.

func (*IPAddr) Network

func (a *IPAddr) Network() string

Network returns the address's network name, "ip".

func (*IPAddr) String

func (a *IPAddr) String() string

type IPConn

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

IPConn is the implementation of the Conn and PacketConn interfaces for IP network connections.

func (*IPConn) Close

func (c *IPConn) Close() error

Close closes the connection.

func (*IPConn) LocalAddr

func (c *IPConn) LocalAddr() Addr

LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.

func (*IPConn) ReadFrom

func (c *IPConn) ReadFrom(b []byte) (int, Addr, error)

ReadFrom implements the PacketConn ReadFrom method.

func (*IPConn) ReadMsgIP

func (c *IPConn) ReadMsgIP(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error)

ReadMsgIP reads a message from c, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags that were set on the message and the source address of the message.

The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

func (*IPConn) SetDeadline

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

SetDeadline implements the Conn SetDeadline method.

func (*IPConn) SetReadDeadline

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

SetReadDeadline implements the Conn SetReadDeadline method.

func (*IPConn) SetWriteDeadline

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

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*IPConn) SyscallConn

func (c *IPConn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

func (*IPConn) WriteTo

func (c *IPConn) WriteTo(b []byte, addr Addr) (int, error)

WriteTo implements the PacketConn WriteTo method.

func (*IPConn) WriteToIP

func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (int, error)

WriteToIP acts like WriteTo but takes an IPAddr.

type IPMask

type IPMask []byte

An IPMask is a bitmask that can be used to manipulate IP addresses for IP addressing and routing.

See type IPNet and func ParseCIDR for details.

func CIDRMask

func CIDRMask(ones, bits int) IPMask

CIDRMask returns an IPMask consisting of 'ones' 1 bits followed by 0s up to a total length of 'bits' bits. For a mask of this form, CIDRMask is the inverse of IPMask.Size.

func IPv4Mask

func IPv4Mask(a, b, c, d byte) IPMask

IPv4Mask returns the IP mask (in 4-byte form) of the IPv4 mask a.b.c.d.

func (IPMask) Size

func (m IPMask) Size() (ones, bits int)

Size returns the number of leading ones and total bits in the mask. If the mask is not in the canonical form--ones followed by zeros--then Size returns 0, 0.

func (IPMask) String

func (m IPMask) String() string

String returns the hexadecimal form of m, with no punctuation.

type IPNet

type IPNet struct {
	IP   IP     // network number
	Mask IPMask // network mask
}

An IPNet represents an IP network.

func (*IPNet) Contains

func (n *IPNet) Contains(ip IP) bool

Contains reports whether the network includes ip.

func (*IPNet) Network

func (n *IPNet) Network() string

Network returns the address's network name, "ip+net".

func (*IPNet) String

func (n *IPNet) String() string

String returns the CIDR notation of n like "192.0.2.0/24" or "2001:db8::/48" as defined in RFC 4632 and RFC 4291. If the mask is not in the canonical form, it returns the string which consists of an IP address, followed by a slash character and a mask expressed as hexadecimal form with no punctuation like "198.51.100.0/c000ff00".

type Interface

type Interface struct {
	Index        int          // positive integer that starts at one, zero is never used
	MTU          int          // maximum transmission unit
	Name         string       // e.g., "en0", "lo0", "eth0.100"
	HardwareAddr HardwareAddr // IEEE MAC-48, EUI-48 and EUI-64 form
	Flags        Flags        // e.g., FlagUp, FlagLoopback, FlagMulticast
}

Interface represents a mapping between network interface name and index. It also represents network interface facility information.

func InterfaceByIndex

func InterfaceByIndex(index int) (*Interface, error)

InterfaceByIndex returns the interface specified by index.

On Solaris, it returns one of the logical network interfaces sharing the logical data link; for more precision use InterfaceByName.

func Interfaces

func Interfaces() ([]Interface, error)

Interfaces returns a list of the system's network interfaces.

type ListenConfig

type ListenConfig struct {
	// If Control is not nil, it is called after creating the network
	// connection but before binding it to the operating system.
	//
	// Network and address parameters passed to Control method are not
	// necessarily the ones passed to Listen. For example, passing "tcp" to
	// Listen will cause the Control function to be called with "tcp4" or "tcp6".
	Control func(network, address string, c syscall.RawConn) error

	// KeepAlive specifies the keep-alive period for network
	// connections accepted by this listener.
	// If zero, keep-alives are enabled if supported by the protocol
	// and operating system. Network protocols or operating systems
	// that do not support keep-alives ignore this field.
	// If negative, keep-alives are disabled.
	KeepAlive time.Duration
	// contains filtered or unexported fields
}

ListenConfig contains options for listening to an address.

func (*ListenConfig) Listen

func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error)

Listen announces on the local network address.

See func Listen for a description of the network and address parameters.

func (*ListenConfig) ListenPacket

func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error)

ListenPacket announces on the local network address.

See func ListenPacket for a description of the network and address parameters.

type Listener

type Listener interface {
	// Accept waits for and returns the next connection to the listener.
	Accept() (Conn, error)

	// Close closes the listener.
	// Any blocked Accept operations will be unblocked and return errors.
	Close() error

	// Addr returns the listener's network address.
	Addr() Addr
}

A Listener is a generic network listener for stream-oriented protocols.

Multiple goroutines may invoke methods on a Listener simultaneously.

func Listen

func Listen(network, address string) (Listener, error)

Listen announces on the local network address.

See Go "net" package Listen() for more information.

Note: Tinygo Listen supports a subset of networks supported by Go Listen, specifically: "tcp", "tcp4". "tcp6" and unix networks are not supported.

type OpError

type OpError struct {
	// Op is the operation which caused the error, such as
	// "read" or "write".
	Op string

	// Net is the network type on which this error occurred,
	// such as "tcp" or "udp6".
	Net string

	// For operations involving a remote network connection, like
	// Dial, Read, or Write, Source is the corresponding local
	// network address.
	Source Addr

	// Addr is the network address for which this error occurred.
	// For local operations, like Listen or SetDeadline, Addr is
	// the address of the local endpoint being manipulated.
	// For operations involving a remote network connection, like
	// Dial, Read, or Write, Addr is the remote address of that
	// connection.
	Addr Addr

	// Err is the error that occurred during the operation.
	// The Error method panics if the error is nil.
	Err error
}

OpError is the error type usually returned by functions in the net package. It describes the operation, network type, and address of an error.

func (*OpError) Error

func (e *OpError) Error() string

func (*OpError) Timeout

func (e *OpError) Timeout() bool

func (*OpError) Unwrap

func (e *OpError) Unwrap() error

type PacketConn

type PacketConn interface {
	// ReadFrom reads a packet from the connection,
	// copying the payload into p. It returns the number of
	// bytes copied into p and the return address that
	// was on the packet.
	// It returns the number of bytes read (0 <= n <= len(p))
	// and any error encountered. Callers should always process
	// the n > 0 bytes returned before considering the error err.
	// ReadFrom can be made to time out and return an error after a
	// fixed time limit; see SetDeadline and SetReadDeadline.
	ReadFrom(p []byte) (n int, addr Addr, err error)

	// WriteTo writes a packet with payload p to addr.
	// WriteTo can be made to time out and return an Error after a
	// fixed time limit; see SetDeadline and SetWriteDeadline.
	// On packet-oriented connections, write timeouts are rare.
	WriteTo(p []byte, addr Addr) (n int, err error)

	// Close closes the connection.
	// Any blocked ReadFrom or WriteTo operations will be unblocked and return errors.
	Close() error

	// LocalAddr returns the local network address, if known.
	LocalAddr() Addr

	// SetDeadline sets the read and write deadlines associated
	// with the connection. It is equivalent to calling both
	// SetReadDeadline and SetWriteDeadline.
	//
	// A deadline is an absolute time after which I/O operations
	// fail instead of blocking. The deadline applies to all future
	// and pending I/O, not just the immediately following call to
	// Read or Write. After a deadline has been exceeded, the
	// connection can be refreshed by setting a deadline in the future.
	//
	// If the deadline is exceeded a call to Read or Write or to other
	// I/O methods will return an error that wraps os.ErrDeadlineExceeded.
	// This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
	// The error's Timeout method will return true, but note that there
	// are other possible errors for which the Timeout method will
	// return true even if the deadline has not been exceeded.
	//
	// An idle timeout can be implemented by repeatedly extending
	// the deadline after successful ReadFrom or WriteTo calls.
	//
	// A zero value for t means I/O operations will not time out.
	SetDeadline(t time.Time) error

	// SetReadDeadline sets the deadline for future ReadFrom calls
	// and any currently-blocked ReadFrom call.
	// A zero value for t means ReadFrom will not time out.
	SetReadDeadline(t time.Time) error

	// SetWriteDeadline sets the deadline for future WriteTo calls
	// and any currently-blocked WriteTo call.
	// Even if write times out, it may return n > 0, indicating that
	// some of the data was successfully written.
	// A zero value for t means WriteTo will not time out.
	SetWriteDeadline(t time.Time) error
}

PacketConn is a generic packet-oriented network connection.

Multiple goroutines may invoke methods on a PacketConn simultaneously.

type ParseError

type ParseError struct {
	// Type is the type of string that was expected, such as
	// "IP address", "CIDR address".
	Type string

	// Text is the malformed text string.
	Text string
}

A ParseError is the error type of literal network address parsers.

func (*ParseError) Error

func (e *ParseError) Error() string

type TCPAddr

type TCPAddr struct {
	IP   IP
	Port int
	Zone string // IPv6 scoped addressing zone
}

TCPAddr represents the address of a TCP end point.

func ResolveTCPAddr

func ResolveTCPAddr(network, address string) (*TCPAddr, error)

ResolveTCPAddr returns an address of TCP end point.

The network must be a TCP network name.

If the host in the address parameter is not a literal IP address or the port is not a literal port number, ResolveTCPAddr resolves the address to an address of TCP end point. Otherwise, it parses the address as a pair of literal IP address and port number. The address parameter can use a host name, but this is not recommended, because it will return at most one of the host name's IP addresses.

See func Dial for a description of the network and address parameters.

func TCPAddrFromAddrPort

func TCPAddrFromAddrPort(addr netip.AddrPort) *TCPAddr

TCPAddrFromAddrPort returns addr as a TCPAddr. If addr.IsValid() is false, then the returned TCPAddr will contain a nil IP field, indicating an address family-agnostic unspecified address.

func (*TCPAddr) AddrPort

func (a *TCPAddr) AddrPort() netip.AddrPort

AddrPort returns the TCPAddr a as a netip.AddrPort.

If a.Port does not fit in a uint16, it's silently truncated.

If a is nil, a zero value is returned.

func (*TCPAddr) Network

func (a *TCPAddr) Network() string

Network returns the address's network name, "tcp".

func (*TCPAddr) String

func (a *TCPAddr) String() string

type TCPConn

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

TCPConn is an implementation of the Conn interface for TCP network connections.

func DialTCP

func DialTCP(network string, laddr, raddr *TCPAddr) (*TCPConn, error)

DialTCP acts like Dial for TCP networks.

The network must be a TCP network name; see func Dial for details.

If laddr is nil, a local address is automatically chosen. If the IP field of raddr is nil or an unspecified IP address, the local system is assumed.

func (*TCPConn) Close

func (c *TCPConn) Close() error

func (*TCPConn) CloseWrite

func (c *TCPConn) CloseWrite() error

func (*TCPConn) LocalAddr

func (c *TCPConn) LocalAddr() Addr

func (*TCPConn) Read

func (c *TCPConn) Read(b []byte) (int, error)

func (*TCPConn) RemoteAddr

func (c *TCPConn) RemoteAddr() Addr

func (*TCPConn) SetDeadline

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

func (*TCPConn) SetKeepAlive

func (c *TCPConn) SetKeepAlive(keepalive bool) error

SetKeepAlive sets whether the operating system should send keep-alive messages on the connection.

func (*TCPConn) SetKeepAlivePeriod

func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error

SetKeepAlivePeriod sets period between keep-alives.

func (*TCPConn) SetLinger

func (c *TCPConn) SetLinger(sec int) error

SetLinger sets the behavior of Close on a connection which still has data waiting to be sent or to be acknowledged.

If sec < 0 (the default), the operating system finishes sending the data in the background.

If sec == 0, the operating system discards any unsent or unacknowledged data.

If sec > 0, the data is sent in the background as with sec < 0. On some operating systems including Linux, this may cause Close to block until all data has been sent or discarded. On some operating systems after sec seconds have elapsed any remaining unsent data may be discarded.

func (*TCPConn) SetReadDeadline

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

func (*TCPConn) SetWriteDeadline

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

func (*TCPConn) SyscallConn

func (c *TCPConn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

func (*TCPConn) Write

func (c *TCPConn) Write(b []byte) (int, error)

type TCPListener

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

TCPListener is a TCP network listener. Clients should typically use variables of type Listener instead of assuming TCP.

func (*TCPListener) Accept

func (l *TCPListener) Accept() (Conn, error)

func (*TCPListener) Addr

func (l *TCPListener) Addr() Addr

func (*TCPListener) Close

func (l *TCPListener) Close() error

type TLSAddr

type TLSAddr struct {
	Host string
	Port int
}

TLSAddr represents the address of a TLS end point.

func (*TLSAddr) Network

func (a *TLSAddr) Network() string

func (*TLSAddr) String

func (a *TLSAddr) String() string

type TLSConn

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

A TLSConn represents a secured connection. It implements the net.Conn interface.

func DialTLS

func DialTLS(addr string) (*TLSConn, error)

func (*TLSConn) Close

func (c *TLSConn) Close() error

func (*TLSConn) Handshake

func (c *TLSConn) Handshake() error

Handshake runs the client or server handshake protocol if it has not yet been run.

Most uses of this package need not call Handshake explicitly: the first Read or Write will call it automatically.

For control over canceling or setting a timeout on a handshake, use HandshakeContext or the Dialer's DialContext method instead.

func (*TLSConn) LocalAddr

func (c *TLSConn) LocalAddr() Addr

func (*TLSConn) Read

func (c *TLSConn) Read(b []byte) (int, error)

func (*TLSConn) RemoteAddr

func (c *TLSConn) RemoteAddr() Addr

func (*TLSConn) SetDeadline

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

func (*TLSConn) SetReadDeadline

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

func (*TLSConn) SetWriteDeadline

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

func (*TLSConn) Write

func (c *TLSConn) Write(b []byte) (int, error)

type UDPAddr

type UDPAddr struct {
	IP   IP
	Port int
	Zone string // IPv6 scoped addressing zone
}

UDPAddr represents the address of a UDP end point.

func ResolveUDPAddr

func ResolveUDPAddr(network, address string) (*UDPAddr, error)

ResolveUDPAddr returns an address of UDP end point.

The network must be a UDP network name.

If the host in the address parameter is not a literal IP address or the port is not a literal port number, ResolveUDPAddr resolves the address to an address of UDP end point. Otherwise, it parses the address as a pair of literal IP address and port number. The address parameter can use a host name, but this is not recommended, because it will return at most one of the host name's IP addresses.

See func Dial for a description of the network and address parameters.

func (*UDPAddr) AddrPort

func (a *UDPAddr) AddrPort() netip.AddrPort

AddrPort returns the UDPAddr a as a netip.AddrPort.

If a.Port does not fit in a uint16, it's silently truncated.

If a is nil, a zero value is returned.

func (*UDPAddr) Network

func (a *UDPAddr) Network() string

Network returns the address's network name, "udp".

func (*UDPAddr) String

func (a *UDPAddr) String() string

type UDPConn

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

UDPConn is the implementation of the Conn and PacketConn interfaces for UDP network connections.

func DialUDP

func DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error)

DialUDP acts like Dial for UDP networks.

The network must be a UDP network name; see func Dial for details.

If laddr is nil, a local address is automatically chosen. If the IP field of raddr is nil or an unspecified IP address, the local system is assumed.

func (*UDPConn) Close

func (c *UDPConn) Close() error

func (*UDPConn) LocalAddr

func (c *UDPConn) LocalAddr() Addr

func (*UDPConn) Read

func (c *UDPConn) Read(b []byte) (int, error)

func (*UDPConn) ReadFrom

func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error)

ReadFrom implements the PacketConn ReadFrom method.

func (*UDPConn) ReadMsgUDP

func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)

ReadMsgUDP reads a message from c, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags that were set on the message and the source address of the message.

The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

func (*UDPConn) RemoteAddr

func (c *UDPConn) RemoteAddr() Addr

func (*UDPConn) SetDeadline

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

func (*UDPConn) SetReadDeadline

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

func (*UDPConn) SetWriteDeadline

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

func (*UDPConn) SyscallConn

func (c *UDPConn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

func (*UDPConn) Write

func (c *UDPConn) Write(b []byte) (int, error)

func (*UDPConn) WriteMsgUDP

func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error)

WriteMsgUDP writes a message to addr via c if c isn't connected, or to c's remote address if c is connected (in which case addr must be nil). The payload is copied from b and the associated out-of-band data is copied from oob. It returns the number of payload and out-of-band bytes written.

The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.

func (*UDPConn) WriteTo

func (c *UDPConn) WriteTo(b []byte, addr Addr) (int, error)

WriteTo implements the PacketConn WriteTo method.

type UnixAddr

type UnixAddr struct {
	Name string
	Net  string
}

UnixAddr represents the address of a Unix domain socket end point.

func ResolveUnixAddr

func ResolveUnixAddr(network, address string) (*UnixAddr, error)

ResolveUnixAddr returns an address of Unix domain socket end point.

The network must be a Unix network name.

See func Dial for a description of the network and address parameters.

func (*UnixAddr) Network

func (a *UnixAddr) Network() string

Network returns the address's network name, "unix", "unixgram" or "unixpacket".

func (*UnixAddr) String

func (a *UnixAddr) String() string

Notes

Bugs

  • On JS, methods and functions related to Interface are not implemented.

  • On AIX, DragonFly BSD, NetBSD, OpenBSD, Plan 9 and Solaris, the MulticastAddrs method of Interface is not implemented.

  • On every POSIX platform, reads from the "ip4" network using the ReadFrom or ReadFromIP method might not return a complete IPv4 packet, including its header, even if there is space available. This can occur even in cases where Read or ReadMsgIP could return a complete packet. For this reason, it is recommended that you do not use these methods if it is important to receive a full packet.

    The Go 1 compatibility guidelines make it impossible for us to change the behavior of these methods; use Read or ReadMsgIP instead.

  • On JS and Plan 9, methods and functions related to IPConn are not implemented.

  • On Windows, the File method of IPConn is not implemented.

  • On JS, WASIP1 and Plan 9, methods and functions related to UnixConn and UnixListener are not implemented.

  • On Windows, methods and functions related to UnixConn and UnixListener don't work for "unixgram" and "unixpacket".

  • On TinyGo, Unix sockets are not implemented.

Directories

Path Synopsis
internal
Package internal contains HTTP internals shared by net/http and net/http/httputil.
Package internal contains HTTP internals shared by net/http and net/http/httputil.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL