Involved Source Filesaddrselect.gocgo_unix.goconf.godial.godnsclient.godnsclient_unix.godnsconfig.godnsconfig_unix.goerror_posix.goerror_unix.gofd_posix.gofd_unix.gofile.gofile_unix.gohook.gohook_unix.gohosts.gointerface.gointerface_linux.goip.goiprawsock.goiprawsock_posix.goipsock.goipsock_posix.golookup.golookup_unix.gomac.gomptcpsock_linux.go Package net provides a portable interface for network I/O, including
TCP/IP, UDP, domain name resolution, and Unix domain sockets.
Although the package provides access to low-level networking
primitives, most clients will need only the basic interface provided
by the Dial, Listen, and Accept functions and the associated
Conn and Listener interfaces. The crypto/tls package uses
the same interfaces and similar Dial and Listen functions.
The Dial function connects to a server:
conn, err := net.Dial("tcp", "golang.org:80")
if err != nil {
// handle error
}
fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
status, err := bufio.NewReader(conn).ReadString('\n')
// ...
The Listen function creates servers:
ln, err := net.Listen("tcp", ":8080")
if err != nil {
// handle error
}
for {
conn, err := ln.Accept()
if err != nil {
// handle error
}
go handleConnection(conn)
}
# Name Resolution
The method for resolving domain names, whether indirectly with functions like Dial
or directly with functions like LookupHost and LookupAddr, varies by operating system.
On Unix systems, the resolver has two options for resolving names.
It can use a pure Go resolver that sends DNS requests directly to the servers
listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C
library routines such as getaddrinfo and getnameinfo.
By default the pure Go resolver is used, because a blocked DNS request consumes
only a goroutine, while a blocked C call consumes an operating system thread.
When cgo is available, the cgo-based resolver is used instead under a variety of
conditions: on systems that do not let programs make direct DNS requests (OS X),
when the LOCALDOMAIN environment variable is present (even if empty),
when the RES_OPTIONS or HOSTALIASES environment variable is non-empty,
when the ASR_CONFIG environment variable is non-empty (OpenBSD only),
when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the
Go resolver does not implement, and when the name being looked up ends in .local
or is an mDNS name.
The resolver decision can be overridden by setting the netdns value of the
GODEBUG environment variable (see package runtime) to go or cgo, as in:
export GODEBUG=netdns=go # force pure Go resolver
export GODEBUG=netdns=cgo # force native resolver (cgo, win32)
The decision can also be forced while building the Go source tree
by setting the netgo or netcgo build tag.
A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver
to print debugging information about its decisions.
To force a particular resolver while also printing debugging information,
join the two settings by a plus sign, as in GODEBUG=netdns=go+1.
On macOS, if Go code that uses the net package is built with
-buildmode=c-archive, linking the resulting archive into a C program
requires passing -lresolv when linking the C code.
On Plan 9, the resolver always accesses /net/cs and /net/dns.
On Windows, in Go 1.18.x and earlier, the resolver always used C
library functions, such as GetAddrInfo and DnsQuery.netcgo_off.gonetgo_off.gonss.goparse.gopipe.goport.goport_unix.gorawconn.gosendfile_linux.gosock_cloexec.gosock_linux.gosock_posix.gosockaddr_posix.gosockopt_linux.gosockopt_posix.gosockoptip_linux.gosockoptip_posix.gosplice_linux.gotcpsock.gotcpsock_posix.gotcpsockopt_posix.gotcpsockopt_unix.goudpsock.goudpsock_posix.gounixsock.gounixsock_posix.gounixsock_readmsg_cmsg_cloexec.gowritev_unix.gocgo_linux.gocgo_resnew.gocgo_socknew.gocgo_unix_cgo.gocgo_unix_cgo_res.go
Code Examples
package main
import (
"fmt"
"net"
)
func main() {
// This mask corresponds to a /31 subnet for IPv4.
fmt.Println(net.CIDRMask(31, 32))
// This mask corresponds to a /64 subnet for IPv6.
fmt.Println(net.CIDRMask(64, 128))
}
package main
import (
"context"
"log"
"net"
"time"
)
func main() {
var d net.Dialer
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
conn, err := d.DialContext(ctx, "tcp", "localhost:12345")
if err != nil {
log.Fatalf("Failed to dial: %v", err)
}
defer conn.Close()
if _, err := conn.Write([]byte("Hello, World!")); err != nil {
log.Fatal(err)
}
}
package main
import (
"context"
"log"
"net"
"time"
)
func main() {
// DialUnix does not take a context.Context parameter. This example shows
// how to dial a Unix socket with a Context. Note that the Context only
// applies to the dial operation; it does not apply to the connection once
// it has been established.
var d net.Dialer
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
d.LocalAddr = nil // if you have a local addr, add it here
raddr := net.UnixAddr{Name: "/path/to/unix.sock", Net: "unix"}
conn, err := d.DialContext(ctx, "unix", raddr.String())
if err != nil {
log.Fatalf("Failed to dial: %v", err)
}
defer conn.Close()
if _, err := conn.Write([]byte("Hello, socket!")); err != nil {
log.Fatal(err)
}
}
package main
import (
"fmt"
"net"
)
func main() {
ip := net.ParseIP("192.0.2.1")
fmt.Println(ip.DefaultMask())
}
package main
import (
"fmt"
"net"
)
func main() {
ipv4DNS := net.ParseIP("8.8.8.8")
ipv4Lo := net.ParseIP("127.0.0.1")
ipv6DNS := net.ParseIP("0:0:0:0:0:FFFF:0808:0808")
fmt.Println(ipv4DNS.Equal(ipv4DNS))
fmt.Println(ipv4DNS.Equal(ipv4Lo))
fmt.Println(ipv4DNS.Equal(ipv6DNS))
}
package main
import (
"fmt"
"net"
)
func main() {
ipv6Global := net.ParseIP("2000::")
ipv6UniqLocal := net.ParseIP("2000::")
ipv6Multi := net.ParseIP("FF00::")
ipv4Private := net.ParseIP("10.255.0.0")
ipv4Public := net.ParseIP("8.8.8.8")
ipv4Broadcast := net.ParseIP("255.255.255.255")
fmt.Println(ipv6Global.IsGlobalUnicast())
fmt.Println(ipv6UniqLocal.IsGlobalUnicast())
fmt.Println(ipv6Multi.IsGlobalUnicast())
fmt.Println(ipv4Private.IsGlobalUnicast())
fmt.Println(ipv4Public.IsGlobalUnicast())
fmt.Println(ipv4Broadcast.IsGlobalUnicast())
}
package main
import (
"fmt"
"net"
)
func main() {
ipv6InterfaceLocalMulti := net.ParseIP("ff01::1")
ipv6Global := net.ParseIP("2000::")
ipv4 := net.ParseIP("255.0.0.0")
fmt.Println(ipv6InterfaceLocalMulti.IsInterfaceLocalMulticast())
fmt.Println(ipv6Global.IsInterfaceLocalMulticast())
fmt.Println(ipv4.IsInterfaceLocalMulticast())
}
package main
import (
"fmt"
"net"
)
func main() {
ipv6LinkLocalMulti := net.ParseIP("ff02::2")
ipv6LinkLocalUni := net.ParseIP("fe80::")
ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
ipv4LinkLocalUni := net.ParseIP("169.254.0.0")
fmt.Println(ipv6LinkLocalMulti.IsLinkLocalMulticast())
fmt.Println(ipv6LinkLocalUni.IsLinkLocalMulticast())
fmt.Println(ipv4LinkLocalMulti.IsLinkLocalMulticast())
fmt.Println(ipv4LinkLocalUni.IsLinkLocalMulticast())
}
package main
import (
"fmt"
"net"
)
func main() {
ipv6LinkLocalUni := net.ParseIP("fe80::")
ipv6Global := net.ParseIP("2000::")
ipv4LinkLocalUni := net.ParseIP("169.254.0.0")
ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
fmt.Println(ipv6LinkLocalUni.IsLinkLocalUnicast())
fmt.Println(ipv6Global.IsLinkLocalUnicast())
fmt.Println(ipv4LinkLocalUni.IsLinkLocalUnicast())
fmt.Println(ipv4LinkLocalMulti.IsLinkLocalUnicast())
}
package main
import (
"fmt"
"net"
)
func main() {
ipv6Lo := net.ParseIP("::1")
ipv6 := net.ParseIP("ff02::1")
ipv4Lo := net.ParseIP("127.0.0.0")
ipv4 := net.ParseIP("128.0.0.0")
fmt.Println(ipv6Lo.IsLoopback())
fmt.Println(ipv6.IsLoopback())
fmt.Println(ipv4Lo.IsLoopback())
fmt.Println(ipv4.IsLoopback())
}
package main
import (
"fmt"
"net"
)
func main() {
ipv6Multi := net.ParseIP("FF00::")
ipv6LinkLocalMulti := net.ParseIP("ff02::1")
ipv6Lo := net.ParseIP("::1")
ipv4Multi := net.ParseIP("239.0.0.0")
ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")
ipv4Lo := net.ParseIP("127.0.0.0")
fmt.Println(ipv6Multi.IsMulticast())
fmt.Println(ipv6LinkLocalMulti.IsMulticast())
fmt.Println(ipv6Lo.IsMulticast())
fmt.Println(ipv4Multi.IsMulticast())
fmt.Println(ipv4LinkLocalMulti.IsMulticast())
fmt.Println(ipv4Lo.IsMulticast())
}
package main
import (
"fmt"
"net"
)
func main() {
ipv6Private := net.ParseIP("fc00::")
ipv6Public := net.ParseIP("fe00::")
ipv4Private := net.ParseIP("10.255.0.0")
ipv4Public := net.ParseIP("11.0.0.0")
fmt.Println(ipv6Private.IsPrivate())
fmt.Println(ipv6Public.IsPrivate())
fmt.Println(ipv4Private.IsPrivate())
fmt.Println(ipv4Public.IsPrivate())
}
package main
import (
"fmt"
"net"
)
func main() {
ipv6Unspecified := net.ParseIP("::")
ipv6Specified := net.ParseIP("fe00::")
ipv4Unspecified := net.ParseIP("0.0.0.0")
ipv4Specified := net.ParseIP("8.8.8.8")
fmt.Println(ipv6Unspecified.IsUnspecified())
fmt.Println(ipv6Specified.IsUnspecified())
fmt.Println(ipv4Unspecified.IsUnspecified())
fmt.Println(ipv4Specified.IsUnspecified())
}
package main
import (
"fmt"
"net"
)
func main() {
ipv4Addr := net.ParseIP("192.0.2.1")
// This mask corresponds to a /24 subnet for IPv4.
ipv4Mask := net.CIDRMask(24, 32)
fmt.Println(ipv4Addr.Mask(ipv4Mask))
ipv6Addr := net.ParseIP("2001:db8:a0b:12f0::1")
// This mask corresponds to a /32 subnet for IPv6.
ipv6Mask := net.CIDRMask(32, 128)
fmt.Println(ipv6Addr.Mask(ipv6Mask))
}
package main
import (
"fmt"
"net"
)
func main() {
ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
ipv4 := net.IPv4(10, 255, 0, 0)
fmt.Println(ipv6.String())
fmt.Println(ipv4.String())
}
package main
import (
"fmt"
"net"
)
func main() {
ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
ipv4 := net.IPv4(10, 255, 0, 0)
fmt.Println(ipv6.To16())
fmt.Println(ipv4.To16())
}
package main
import (
"fmt"
"net"
)
func main() {
ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
ipv4 := net.IPv4(10, 255, 0, 0)
fmt.Println(ipv6.To4())
fmt.Println(ipv4.To4())
}
package main
import (
"fmt"
"net"
)
func main() {
fmt.Println(net.IPv4(8, 8, 8, 8))
}
package main
import (
"fmt"
"net"
)
func main() {
fmt.Println(net.IPv4Mask(255, 255, 255, 0))
}
package main
import (
"io"
"log"
"net"
)
func main() {
// Listen on TCP port 2000 on all available unicast and
// anycast IP addresses of the local system.
l, err := net.Listen("tcp", ":2000")
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
// Wait for a connection.
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
// Handle the connection in a new goroutine.
// The loop then returns to accepting, so that
// multiple connections may be served concurrently.
go func(c net.Conn) {
// Echo all incoming data.
io.Copy(c, c)
// Shut down the connection.
c.Close()
}(conn)
}
}
package main
import (
"fmt"
"log"
"net"
)
func main() {
ipv4Addr, ipv4Net, err := net.ParseCIDR("192.0.2.1/24")
if err != nil {
log.Fatal(err)
}
fmt.Println(ipv4Addr)
fmt.Println(ipv4Net)
ipv6Addr, ipv6Net, err := net.ParseCIDR("2001:db8:a0b:12f0::1/32")
if err != nil {
log.Fatal(err)
}
fmt.Println(ipv6Addr)
fmt.Println(ipv6Net)
}
package main
import (
"fmt"
"net"
)
func main() {
fmt.Println(net.ParseIP("192.0.2.1"))
fmt.Println(net.ParseIP("2001:db8::68"))
fmt.Println(net.ParseIP("192.0.2"))
}
package main
import (
"log"
"net"
)
func main() {
// Unlike Dial, ListenPacket creates a connection without any
// association with peers.
conn, err := net.ListenPacket("udp", ":0")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
dst, err := net.ResolveUDPAddr("udp", "192.0.2.1:2000")
if err != nil {
log.Fatal(err)
}
// The connection can write data to the desired address.
_, err = conn.WriteTo([]byte("data"), dst)
if err != nil {
log.Fatal(err)
}
}
Package-Level Type Names (total 102, in which 35 are exported)
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"). 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. 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.(*Buffers) consume(n int64)
*Buffers : io.Reader
*Buffers : io.WriterTo
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. Cancel is an optional channel whose closure indicates that
the dial should be canceled. Not all types of dials support
cancellation.
Deprecated: Use DialContext instead. If Control is not nil, it is called after creating the network
connection but before actually dialing.
Network and address parameters passed to Control function are not
necessarily the ones passed to Dial. For example, passing "tcp" to Dial
will cause the Control function to be called with "tcp4" or "tcp6".
Control is ignored if ControlContext is not nil. If ControlContext is not nil, it is called after creating the network
connection but before actually dialing.
Network and address parameters passed to ControlContext function are not
necessarily the ones passed to Dial. For example, passing "tcp" to Dial
will cause the ControlContext function to be called with "tcp4" or "tcp6".
If ControlContext is not nil, Control is ignored. 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. DualStack previously enabled RFC 6555 Fast Fallback
support, also known as "Happy Eyeballs", in which IPv4 is
tried soon if IPv6 appears to be misconfigured and
hanging.
Deprecated: Fast Fallback is enabled by default. To
disable, set FallbackDelay to a negative value. FallbackDelay specifies the length of time to wait before
spawning a RFC 6555 Fast Fallback connection. That is, this
is the amount of time to wait for IPv6 to succeed before
assuming that IPv6 is misconfigured and falling back to
IPv4.
If zero, a default delay of 300ms is used.
A negative value disables Fast Fallback support. 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. 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. Resolver optionally specifies an alternate resolver to use. 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. If mptcpStatus is set to a value allowing Multipath TCP (MPTCP) to be
used, any call to Dial with "tcp(4|6)" as network will use MPTCP if
supported by the operating system. 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. 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. MultipathTCP reports whether MPTCP will be used.
This method doesn't check if MPTCP is supported by the operating
system or not. SetMultipathTCP directs the Dial methods to use, or not use, MPTCP,
if supported by the operating system. This method overrides the
system default and the GODEBUG=multipathtcp=... setting if any.
If MPTCP is not available on the host or not supported by the server,
the Dial methods will fall back to TCP. deadline returns the earliest of:
- now+Timeout
- d.Deadline
- the context's deadline
Or zero, if none of Timeout, Deadline, or context's deadline is set.(*Dialer) dualStack() bool(*Dialer) fallbackDelay() time.Duration(*Dialer) resolver() *Resolver
*Dialer : golang.org/x/net/proxy.ContextDialer
*Dialer : golang.org/x/net/proxy.Dialer
func crypto/tls.(*Dialer).netDialer() *Dialer
func crypto/tls.DialWithDialer(dialer *Dialer, network, addr string, config *tls.Config) (*tls.Conn, error)
func net/http.defaultTransportDialContext(dialer *Dialer) func(context.Context, string, string) (Conn, error)
func crypto/tls.dial(ctx context.Context, netDialer *Dialer, network, addr string, config *tls.Config) (*tls.Conn, error)
var net/http.zeroDialer
DNSConfigError represents an error reading the machine's DNS configuration.
(No longer used; kept for compatibility.)Errerror(*DNSConfigError) Error() string(*DNSConfigError) Temporary() bool(*DNSConfigError) Timeout() bool(*DNSConfigError) Unwrap() error
*DNSConfigError : Error
*DNSConfigError : error
*DNSConfigError : github.com/go-faster/errors.Wrapper
*DNSConfigError : temporary
*DNSConfigError : timeout
*DNSConfigError : os.timeout
DNSError represents a DNS lookup error. // description of the error // if true, host could not be found // if true, error is temporary; not all errors set this // if true, timed out; not all timeouts set this // name looked for // server used(*DNSError) Error() string Temporary reports whether the DNS error is known to be temporary.
This is not always known; a DNS lookup may fail due to a temporary
error and return a DNSError for which Temporary returns false. Timeout reports whether the DNS lookup is known to have timed out.
This is not always known; a DNS lookup may fail due to a timeout
and return a DNSError for which Timeout returns false.
*DNSError : Error
*DNSError : error
*DNSError : temporary
*DNSError : timeout
*DNSError : os.timeout
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. 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. 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. 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. IsInterfaceLocalMulticast reports whether ip is
an interface-local multicast address. IsLinkLocalMulticast reports whether ip is a link-local
multicast address. IsLinkLocalUnicast reports whether ip is a link-local
unicast address. IsLoopback reports whether ip is a loopback address. IsMulticast reports whether ip is a multicast address. IsPrivate reports whether ip is a private address, according to
RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses). IsUnspecified reports whether ip is an unspecified address, either
the IPv4 address "0.0.0.0" or the IPv6 address "::". 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. Mask returns the result of masking the IP address ip with mask. 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 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. To4 converts the IPv4 address ip to a 4-byte representation.
If ip is not an IPv4 address, To4 returns nil. UnmarshalText implements the encoding.TextUnmarshaler interface.
The IP address is expected in a form accepted by ParseIP.( IP) matchAddrFamily(x IP) bool
IP : encoding.TextMarshaler
*IP : encoding.TextUnmarshaler
IP : fmt.Stringer
IP : context.stringer
IP : runtime.stringer
func IPv4(a, b, c, d byte) IP
func LookupIP(host string) ([]IP, error)
func ParseCIDR(s string) (IP, *IPNet, error)
func ParseIP(s string) IP
func IP.Mask(mask IPMask) IP
func IP.To16() IP
func IP.To4() IP
func (*Resolver).LookupIP(ctx context.Context, network, host string) ([]IP, error)
func copyIP(x IP) IP
func interfaceToIPv4Addr(ifi *Interface) (IP, error)
func loopbackIP(net string) IP
func networkNumberAndMask(n *IPNet) (ip IP, m IPMask)
func crypto/x509.parseSANExtension(der cryptobyte.String) (dnsNames, emailAddresses []string, ipAddresses []IP, uris []*url.URL, err error)
func IP.Equal(x IP) bool
func (*IPNet).Contains(ip IP) bool
func golang.org/x/net/proxy.(*PerHost).AddIP(ip IP)
func cgoSockaddr(ip IP, zone string) (*_C_struct_sockaddr, _C_socklen_t)
func cgoSockaddrInet4(ip IP) *_Ctype_struct_sockaddr
func cgoSockaddrInet6(ip IP, zone int) *_Ctype_struct_sockaddr
func commonPrefixLen(a netip.Addr, b IP) (cpl int)
func copyIP(x IP) IP
func ipEmptyString(ip IP) string
func ipToSockaddr(family int, ip IP, port int, zone string) (syscall.Sockaddr, error)
func ipToSockaddrInet4(ip IP, port int) (syscall.SockaddrInet4, error)
func ipToSockaddrInet6(ip IP, port int, zone string) (syscall.SockaddrInet6, error)
func ipv4AddrToInterface(ip IP) (*Interface, error)
func isZeros(p IP) bool
func joinIPv4Group(fd *netFD, ifi *Interface, ip IP) error
func joinIPv6Group(fd *netFD, ifi *Interface, ip IP) error
func listenIPv4MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error
func listenIPv6MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error
func IP.matchAddrFamily(x IP) bool
func crypto/x509.marshalSANs(dnsNames, emailAddresses []string, ipAddresses []IP, uris []*url.URL) (derBytes []byte, err error)
func crypto/x509.matchIPConstraint(ip IP, constraint *IPNet) (bool, error)
var IPv4allrouter
var IPv4allsys
var IPv4bcast
var IPv4zero
var IPv6interfacelocalallnodes
var IPv6linklocalallnodes
var IPv6linklocalallrouters
var IPv6loopback
var IPv6unspecified
var IPv6zero
IPConn is the implementation of the Conn and PacketConn interfaces
for IP network connections.connconnconn.fd*netFD Close closes the connection. File returns a copy of the underlying os.File.
It is the caller's responsibility to close f when finished.
Closing c does not affect f, and closing f does not affect c.
The returned os.File's file descriptor is different from the connection's.
Attempting to change properties of the original using this duplicate
may or may not have the desired effect. LocalAddr returns the local network address.
The Addr returned is shared by all invocations of LocalAddr, so
do not modify it. Read implements the Conn Read method. ReadFrom implements the PacketConn ReadFrom method. ReadFromIP acts like ReadFrom but returns an IPAddr. 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. RemoteAddr returns the remote network address.
The Addr returned is shared by all invocations of RemoteAddr, so
do not modify it. SetDeadline implements the Conn SetDeadline method. SetReadBuffer sets the size of the operating system's
receive buffer associated with the connection. SetReadDeadline implements the Conn SetReadDeadline method. SetWriteBuffer sets the size of the operating system's
transmit buffer associated with the connection. SetWriteDeadline implements the Conn SetWriteDeadline method. SyscallConn returns a raw network connection.
This implements the syscall.Conn interface. Write implements the Conn Write method. WriteMsgIP writes a message to addr via c, copying the payload from
b and the associated out-of-band data 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. WriteTo implements the PacketConn WriteTo method. WriteToIP acts like WriteTo but takes an IPAddr.(*IPConn) ok() bool(*IPConn) readFrom(b []byte) (int, *IPAddr, error)(*IPConn) readMsg(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error)(*IPConn) writeBuffers(v *Buffers) (int64, error)(*IPConn) writeMsg(b, oob []byte, addr *IPAddr) (n, oobn int, err error)(*IPConn) writeTo(b []byte, addr *IPAddr) (int, error)
*IPConn : Conn
*IPConn : PacketConn
*IPConn : internal/bisect.Writer
*IPConn : io.Closer
*IPConn : io.ReadCloser
*IPConn : io.Reader
*IPConn : io.ReadWriteCloser
*IPConn : io.ReadWriter
*IPConn : io.WriteCloser
*IPConn : io.Writer
*IPConn : syscall.Conn
*IPConn : buffersWriter
*IPConn : crypto/tls.transcriptHash
func DialIP(network string, laddr, raddr *IPAddr) (*IPConn, error)
func ListenIP(network string, laddr *IPAddr) (*IPConn, error)
func newIPConn(fd *netFD) *IPConn
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. 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. String returns the hexadecimal form of m, with no punctuation.
IPMask : fmt.Stringer
IPMask : context.stringer
IPMask : runtime.stringer
func CIDRMask(ones, bits int) IPMask
func IPv4Mask(a, b, c, d byte) IPMask
func IP.DefaultMask() IPMask
func networkNumberAndMask(n *IPNet) (ip IP, m IPMask)
func IP.Mask(mask IPMask) IP
func simpleMaskLength(mask IPMask) int
var classAMask
var classBMask
var classCMask
An IPNet represents an IP network. // network number // network mask Contains reports whether the network includes ip. Network returns the address's network name, "ip+net". 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".
*IPNet : Addr
*IPNet : fmt.Stringer
*IPNet : context.stringer
*IPNet : runtime.stringer
func ParseCIDR(s string) (IP, *IPNet, error)
func golang.org/x/net/proxy.(*PerHost).AddNetwork(net *IPNet)
func networkNumberAndMask(n *IPNet) (ip IP, m IPMask)
func crypto/x509.matchIPConstraint(ip IP, constraint *IPNet) (bool, error)
ListenConfig contains options for listening to an address. 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". 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. If mptcpStatus is set to a value allowing Multipath TCP (MPTCP) to be
used, any call to Listen with "tcp(4|6)" as network will use MPTCP if
supported by the operating system. Listen announces on the local network address.
See func Listen for a description of the network and address
parameters. ListenPacket announces on the local network address.
See func ListenPacket for a description of the network and address
parameters. MultipathTCP reports whether MPTCP will be used.
This method doesn't check if MPTCP is supported by the operating
system or not. SetMultipathTCP directs the Listen method to use, or not use, MPTCP,
if supported by the operating system. This method overrides the
system default and the GODEBUG=multipathtcp=... setting if any.
If MPTCP is not available on the host or not supported by the client,
the Listen method will fall back to TCP.
OpError is the error type usually returned by functions in the net
package. It describes the operation, network type, and address of
an error. 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. Err is the error that occurred during the operation.
The Error method panics if the error is nil. Net is the network type on which this error occurred,
such as "tcp" or "udp6". Op is the operation which caused the error, such as
"read" or "write". For operations involving a remote network connection, like
Dial, Read, or Write, Source is the corresponding local
network address.(*OpError) Error() string(*OpError) Temporary() bool(*OpError) Timeout() bool(*OpError) Unwrap() error
*OpError : Error
*OpError : error
*OpError : github.com/go-faster/errors.Wrapper
*OpError : temporary
*OpError : timeout
*OpError : os.timeout
PacketConn is a generic packet-oriented network connection.
Multiple goroutines may invoke methods on a PacketConn simultaneously. Close closes the connection.
Any blocked ReadFrom or WriteTo operations will be unblocked and return errors. LocalAddr returns the local network address, if known. 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. 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. 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. 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. 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.
*IPConn
*UDPConn
*UnixConn
*github.com/gotd/neo.PacketConn
PacketConn : io.Closer
func FilePacketConn(f *os.File) (c PacketConn, err error)
func ListenPacket(network, address string) (PacketConn, error)
func (*ListenConfig).ListenPacket(ctx context.Context, network, address string) (PacketConn, error)
func github.com/gotd/neo.(*Net).ListenPacket(network, address string) (PacketConn, error)
func filePacketConn(f *os.File) (PacketConn, error)
A ParseError is the error type of literal network address parsers. Text is the malformed text string. Type is the type of string that was expected, such as
"IP address", "CIDR address".(*ParseError) Error() string(*ParseError) Temporary() bool(*ParseError) Timeout() bool
*ParseError : Error
*ParseError : error
*ParseError : temporary
*ParseError : timeout
*ParseError : os.timeout
A Resolver looks up names and numbers.
A nil *Resolver is equivalent to a zero Resolver. Dial optionally specifies an alternate dialer for use by
Go's built-in DNS resolver to make TCP and UDP connections
to DNS services. The host in the address parameter will
always be a literal IP address and not a host name, and the
port in the address parameter will be a literal port number
and not a service name.
If the Conn returned is also a PacketConn, sent and received DNS
messages must adhere to RFC 1035 section 4.2.1, "UDP usage".
Otherwise, DNS messages transmitted over Conn must adhere
to RFC 7766 section 5, "Transport Protocol Selection".
If nil, the default dialer is used. PreferGo controls whether Go's built-in DNS resolver is preferred
on platforms where it's available. It is equivalent to setting
GODEBUG=netdns=go, but scoped to just this resolver. StrictErrors controls the behavior of temporary errors
(including timeout, socket errors, and SERVFAIL) when using
Go's built-in resolver. For a query composed of multiple
sub-queries (such as an A+AAAA address lookup, or walking the
DNS search list), this option causes such errors to abort the
whole query instead of returning a partial result. This is
not enabled by default because it may affect compatibility
with resolvers that process AAAA queries incorrectly. lookupGroup merges LookupIPAddr calls together for lookups for the same
host. The lookupGroup key is the LookupIPAddr.host argument.
The return values are ([]IPAddr, error). LookupAddr performs a reverse lookup for the given address, returning a list
of names mapping to that address.
The returned names are validated to be properly formatted presentation-format
domain names. If the response contains invalid names, those records are filtered
out and an error will be returned alongside the remaining results, if any. LookupCNAME returns the canonical name for the given host.
Callers that do not care about the canonical name can call
LookupHost or LookupIP directly; both take care of resolving
the canonical name as part of the lookup.
A canonical name is the final name after following zero
or more CNAME records.
LookupCNAME does not return an error if host does not
contain DNS "CNAME" records, as long as host resolves to
address records.
The returned canonical name is validated to be a properly
formatted presentation-format domain name. LookupHost looks up the given host using the local resolver.
It returns a slice of that host's addresses. LookupIP looks up host for the given network using the local resolver.
It returns a slice of that host's IP addresses of the type specified by
network.
network must be one of "ip", "ip4" or "ip6". LookupIPAddr looks up host using the local resolver.
It returns a slice of that host's IPv4 and IPv6 addresses. LookupMX returns the DNS MX records for the given domain name sorted by preference.
The returned mail server names are validated to be properly
formatted presentation-format domain names. If the response contains
invalid names, those records are filtered out and an error
will be returned alongside the remaining results, if any. LookupNS returns the DNS NS records for the given domain name.
The returned name server names are validated to be properly
formatted presentation-format domain names. If the response contains
invalid names, those records are filtered out and an error
will be returned alongside the remaining results, if any. LookupNetIP looks up host using the local resolver.
It returns a slice of that host's IP addresses of the type specified by
network.
The network must be one of "ip", "ip4" or "ip6". LookupPort looks up the port for the given network and service. LookupSRV tries to resolve an SRV query of the given service,
protocol, and domain name. The proto is "tcp" or "udp".
The returned records are sorted by priority and randomized
by weight within a priority.
LookupSRV constructs the DNS name to look up following RFC 2782.
That is, it looks up _service._proto.name. To accommodate services
publishing SRV records under non-standard names, if both service
and proto are empty strings, LookupSRV looks up name directly.
The returned service names are validated to be properly
formatted presentation-format domain names. If the response contains
invalid names, those records are filtered out and an error
will be returned alongside the remaining results, if any. LookupTXT returns the DNS TXT records for the given domain name. dial makes a new connection to the provided server (which must be
an IP address) with the provided network type, using either r.Dial
(if both r and r.Dial are non-nil) or else Dialer.DialContext. exchange sends a query on the connection and hopes for a response.(*Resolver) getLookupGroup() *singleflight.Group goLookupCNAME is the native Go (non-cgo) implementation of LookupCNAME.(*Resolver) goLookupHostOrder(ctx context.Context, name string, order hostLookupOrder, conf *dnsConfig) (addrs []string, err error) goLookupIP is the native Go implementation of LookupIP.
The libc versions are in cgo_*.go.(*Resolver) goLookupIPCNAMEOrder(ctx context.Context, network, name string, order hostLookupOrder, conf *dnsConfig) (addrs []IPAddr, cname dnsmessage.Name, err error) goLookupMX returns the MX records for name. goLookupNS returns the NS records for name. goLookupPTR is the native Go implementation of LookupAddr. goLookupSRV returns the SRV records for a target name, built either
from its component service ("sip"), protocol ("tcp"), and name
("example.com."), or from name directly (if service and proto are
both empty).
In either case, the returned target name ("_sip._tcp.example.com.")
is also returned on success.
The records are sorted by weight. goLookupTXT returns the TXT records from name. internetAddrList resolves addr, which may be a literal IP
address or a DNS name, and returns a list of internet protocol
family addresses. The result contains at least one address when
error is nil.(*Resolver) lookup(ctx context.Context, name string, qtype dnsmessage.Type, conf *dnsConfig) (dnsmessage.Parser, string, error)(*Resolver) lookupAddr(ctx context.Context, addr string) ([]string, error)(*Resolver) lookupCNAME(ctx context.Context, name string) (string, error)(*Resolver) lookupHost(ctx context.Context, host string) (addrs []string, err error)(*Resolver) lookupIP(ctx context.Context, network, host string) (addrs []IPAddr, err error) lookupIPAddr looks up host using the local resolver and particular network.
It returns a slice of that host's IPv4 and IPv6 addresses.(*Resolver) lookupMX(ctx context.Context, name string) ([]*MX, error)(*Resolver) lookupNS(ctx context.Context, name string) ([]*NS, error)(*Resolver) lookupPort(ctx context.Context, network, service string) (int, error)(*Resolver) lookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error)(*Resolver) lookupTXT(ctx context.Context, name string) ([]string, error)(*Resolver) preferGo() bool resolveAddrList resolves addr using hint and returns a list of
addresses. The result contains at least one address when error is
nil.(*Resolver) strictErrors() bool Do a lookup for a single name, which must be rooted
(otherwise answer will not find the answers).
func (*Dialer).resolver() *Resolver
var DefaultResolver *Resolver
TCPConn is an implementation of the Conn interface for TCP network
connections.connconnconn.fd*netFD Close closes the connection. CloseRead shuts down the reading side of the TCP connection.
Most callers should just use Close. CloseWrite shuts down the writing side of the TCP connection.
Most callers should just use Close. File returns a copy of the underlying os.File.
It is the caller's responsibility to close f when finished.
Closing c does not affect f, and closing f does not affect c.
The returned os.File's file descriptor is different from the connection's.
Attempting to change properties of the original using this duplicate
may or may not have the desired effect. LocalAddr returns the local network address.
The Addr returned is shared by all invocations of LocalAddr, so
do not modify it. MultipathTCP reports whether the ongoing connection is using MPTCP.
If Multipath TCP is not supported by the host, by the other peer or
intentionally / accidentally filtered out by a device in between, a
fallback to TCP will be done. This method does its best to check if
MPTCP is still being used or not.
On Linux, more conditions are verified on kernels >= v5.16, improving
the results. Read implements the Conn Read method. ReadFrom implements the io.ReaderFrom ReadFrom method. RemoteAddr returns the remote network address.
The Addr returned is shared by all invocations of RemoteAddr, so
do not modify it. SetDeadline implements the Conn SetDeadline method. SetKeepAlive sets whether the operating system should send
keep-alive messages on the connection. SetKeepAlivePeriod sets period between keep-alives. 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. SetNoDelay controls whether the operating system should delay
packet transmission in hopes of sending fewer packets (Nagle's
algorithm). The default is true (no delay), meaning that data is
sent as soon as possible after a Write. SetReadBuffer sets the size of the operating system's
receive buffer associated with the connection. SetReadDeadline implements the Conn SetReadDeadline method. SetWriteBuffer sets the size of the operating system's
transmit buffer associated with the connection. SetWriteDeadline implements the Conn SetWriteDeadline method. SyscallConn returns a raw network connection.
This implements the syscall.Conn interface. Write implements the Conn Write method.(*TCPConn) ok() bool(*TCPConn) readFrom(r io.Reader) (int64, error)(*TCPConn) writeBuffers(v *Buffers) (int64, error)
*TCPConn : Conn
*TCPConn : internal/bisect.Writer
*TCPConn : io.Closer
*TCPConn : io.ReadCloser
*TCPConn : io.Reader
*TCPConn : io.ReaderFrom
*TCPConn : io.ReadWriteCloser
*TCPConn : io.ReadWriter
*TCPConn : io.WriteCloser
*TCPConn : io.Writer
*TCPConn : syscall.Conn
*TCPConn : buffersWriter
*TCPConn : net/http.closeWriter
*TCPConn : crypto/tls.transcriptHash
func DialTCP(network string, laddr, raddr *TCPAddr) (*TCPConn, error)
func (*TCPListener).AcceptTCP() (*TCPConn, error)
func newTCPConn(fd *netFD, keepAlive time.Duration, keepAliveHook func(time.Duration)) *TCPConn
func (*TCPListener).accept() (*TCPConn, error)
TCPListener is a TCP network listener. Clients should typically
use variables of type Listener instead of assuming TCP.fd*netFDlcListenConfig Accept implements the Accept method in the Listener interface; it
waits for the next call and returns a generic Conn. AcceptTCP accepts the next incoming call and returns the new
connection. Addr returns the listener's network address, a *TCPAddr.
The Addr returned is shared by all invocations of Addr, so
do not modify it. Close stops listening on the TCP address.
Already Accepted connections are not closed. File returns a copy of the underlying os.File.
It is the caller's responsibility to close f when finished.
Closing l does not affect f, and closing f does not affect l.
The returned os.File's file descriptor is different from the
connection's. Attempting to change properties of the original
using this duplicate may or may not have the desired effect. SetDeadline sets the deadline associated with the listener.
A zero time value disables the deadline. SyscallConn returns a raw network connection.
This implements the syscall.Conn interface.
The returned RawConn only supports calling Control. Read and
Write return an error.(*TCPListener) accept() (*TCPConn, error)(*TCPListener) close() error(*TCPListener) file() (*os.File, error)(*TCPListener) ok() bool
*TCPListener : Listener
*TCPListener : io.Closer
*TCPListener : syscall.Conn
func ListenTCP(network string, laddr *TCPAddr) (*TCPListener, error)
UDPConn is the implementation of the Conn and PacketConn interfaces
for UDP network connections.connconnconn.fd*netFD Close closes the connection. File returns a copy of the underlying os.File.
It is the caller's responsibility to close f when finished.
Closing c does not affect f, and closing f does not affect c.
The returned os.File's file descriptor is different from the connection's.
Attempting to change properties of the original using this duplicate
may or may not have the desired effect. LocalAddr returns the local network address.
The Addr returned is shared by all invocations of LocalAddr, so
do not modify it. Read implements the Conn Read method. ReadFrom implements the PacketConn ReadFrom method. ReadFromUDP acts like ReadFrom but returns a UDPAddr. ReadFromUDPAddrPort acts like ReadFrom but returns a netip.AddrPort.
If c is bound to an unspecified address, the returned
netip.AddrPort's address might be an IPv4-mapped IPv6 address.
Use netip.Addr.Unmap to get the address without the IPv6 prefix. 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. ReadMsgUDPAddrPort is like ReadMsgUDP but returns an netip.AddrPort instead of a UDPAddr. RemoteAddr returns the remote network address.
The Addr returned is shared by all invocations of RemoteAddr, so
do not modify it. SetDeadline implements the Conn SetDeadline method. SetReadBuffer sets the size of the operating system's
receive buffer associated with the connection. SetReadDeadline implements the Conn SetReadDeadline method. SetWriteBuffer sets the size of the operating system's
transmit buffer associated with the connection. SetWriteDeadline implements the Conn SetWriteDeadline method. SyscallConn returns a raw network connection.
This implements the syscall.Conn interface. Write implements the Conn Write method. 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. WriteMsgUDPAddrPort is like WriteMsgUDP but takes a netip.AddrPort instead of a UDPAddr. WriteTo implements the PacketConn WriteTo method. WriteToUDP acts like WriteTo but takes a UDPAddr. WriteToUDPAddrPort acts like WriteTo but takes a netip.AddrPort.(*UDPConn) ok() bool(*UDPConn) readFrom(b []byte, addr *UDPAddr) (int, *UDPAddr, error)(*UDPConn) readFromAddrPort(b []byte) (n int, addr netip.AddrPort, err error) readFromUDP implements ReadFromUDP.(*UDPConn) readMsg(b, oob []byte) (n, oobn, flags int, addr netip.AddrPort, err error)(*UDPConn) writeBuffers(v *Buffers) (int64, error)(*UDPConn) writeMsg(b, oob []byte, addr *UDPAddr) (n, oobn int, err error)(*UDPConn) writeMsgAddrPort(b, oob []byte, addr netip.AddrPort) (n, oobn int, err error)(*UDPConn) writeTo(b []byte, addr *UDPAddr) (int, error)(*UDPConn) writeToAddrPort(b []byte, addr netip.AddrPort) (int, error)
*UDPConn : Conn
*UDPConn : PacketConn
*UDPConn : internal/bisect.Writer
*UDPConn : io.Closer
*UDPConn : io.ReadCloser
*UDPConn : io.Reader
*UDPConn : io.ReadWriteCloser
*UDPConn : io.ReadWriter
*UDPConn : io.WriteCloser
*UDPConn : io.Writer
*UDPConn : syscall.Conn
*UDPConn : buffersWriter
*UDPConn : crypto/tls.transcriptHash
func DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error)
func ListenMulticastUDP(network string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)
func ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error)
func newUDPConn(fd *netFD) *UDPConn
func listenIPv4MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error
func listenIPv6MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error
UnixConn is an implementation of the Conn interface for connections
to Unix domain sockets.connconnconn.fd*netFD Close closes the connection. CloseRead shuts down the reading side of the Unix domain connection.
Most callers should just use Close. CloseWrite shuts down the writing side of the Unix domain connection.
Most callers should just use Close. File returns a copy of the underlying os.File.
It is the caller's responsibility to close f when finished.
Closing c does not affect f, and closing f does not affect c.
The returned os.File's file descriptor is different from the connection's.
Attempting to change properties of the original using this duplicate
may or may not have the desired effect. LocalAddr returns the local network address.
The Addr returned is shared by all invocations of LocalAddr, so
do not modify it. Read implements the Conn Read method. ReadFrom implements the PacketConn ReadFrom method. ReadFromUnix acts like ReadFrom but returns a UnixAddr. ReadMsgUnix 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.
Note that if len(b) == 0 and len(oob) > 0, this function will still
read (and discard) 1 byte from the connection. RemoteAddr returns the remote network address.
The Addr returned is shared by all invocations of RemoteAddr, so
do not modify it. SetDeadline implements the Conn SetDeadline method. SetReadBuffer sets the size of the operating system's
receive buffer associated with the connection. SetReadDeadline implements the Conn SetReadDeadline method. SetWriteBuffer sets the size of the operating system's
transmit buffer associated with the connection. SetWriteDeadline implements the Conn SetWriteDeadline method. SyscallConn returns a raw network connection.
This implements the syscall.Conn interface. Write implements the Conn Write method. WriteMsgUnix writes a message to addr via c, copying the payload
from b and the associated out-of-band data from oob. It returns the
number of payload and out-of-band bytes written.
Note that if len(b) == 0 and len(oob) > 0, this function will still
write 1 byte to the connection. WriteTo implements the PacketConn WriteTo method. WriteToUnix acts like WriteTo but takes a UnixAddr.(*UnixConn) ok() bool(*UnixConn) readFrom(b []byte) (int, *UnixAddr, error)(*UnixConn) readMsg(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error)(*UnixConn) writeBuffers(v *Buffers) (int64, error)(*UnixConn) writeMsg(b, oob []byte, addr *UnixAddr) (n, oobn int, err error)(*UnixConn) writeTo(b []byte, addr *UnixAddr) (int, error)
*UnixConn : Conn
*UnixConn : PacketConn
*UnixConn : internal/bisect.Writer
*UnixConn : io.Closer
*UnixConn : io.ReadCloser
*UnixConn : io.Reader
*UnixConn : io.ReadWriteCloser
*UnixConn : io.ReadWriter
*UnixConn : io.WriteCloser
*UnixConn : io.Writer
*UnixConn : syscall.Conn
*UnixConn : buffersWriter
*UnixConn : net/http.closeWriter
*UnixConn : crypto/tls.transcriptHash
func DialUnix(network string, laddr, raddr *UnixAddr) (*UnixConn, error)
func ListenUnixgram(network string, laddr *UnixAddr) (*UnixConn, error)
func (*UnixListener).AcceptUnix() (*UnixConn, error)
func newUnixConn(fd *netFD) *UnixConn
func (*UnixListener).accept() (*UnixConn, error)
UnixListener is a Unix domain socket listener. Clients should
typically use variables of type Listener instead of assuming Unix
domain sockets.fd*netFDpathstringunlinkboolunlinkOncesync.Once Accept implements the Accept method in the Listener interface.
Returned connections will be of type *UnixConn. AcceptUnix accepts the next incoming call and returns the new
connection. Addr returns the listener's network address.
The Addr returned is shared by all invocations of Addr, so
do not modify it. Close stops listening on the Unix address. Already accepted
connections are not closed. File returns a copy of the underlying os.File.
It is the caller's responsibility to close f when finished.
Closing l does not affect f, and closing f does not affect l.
The returned os.File's file descriptor is different from the
connection's. Attempting to change properties of the original
using this duplicate may or may not have the desired effect. SetDeadline sets the deadline associated with the listener.
A zero time value disables the deadline. SetUnlinkOnClose sets whether the underlying socket file should be removed
from the file system when the listener is closed.
The default behavior is to unlink the socket file only when package net created it.
That is, when the listener and the underlying socket file were created by a call to
Listen or ListenUnix, then by default closing the listener will remove the socket file.
but if the listener was created by a call to FileListener to use an already existing
socket file, then by default closing the listener will not remove the socket file. SyscallConn returns a raw network connection.
This implements the syscall.Conn interface.
The returned RawConn only supports calling Control. Read and
Write return an error.(*UnixListener) accept() (*UnixConn, error)(*UnixListener) close() error(*UnixListener) file() (*os.File, error)(*UnixListener) ok() bool
*UnixListener : Listener
*UnixListener : io.Closer
*UnixListener : syscall.Conn
func ListenUnix(network string, laddr *UnixAddr) (*UnixListener, error)
An addrinfoErrno represents a getaddrinfo, getnameinfo-specific
error number. It's a signed number and a zero value is a non-error
by convention.( addrinfoErrno) Error() string( addrinfoErrno) Temporary() bool( addrinfoErrno) Timeout() bool isAddrinfoErrno is just for testing purposes.
addrinfoErrno : Error
addrinfoErrno : error
addrinfoErrno : temporary
addrinfoErrno : timeout
addrinfoErrno : os.timeout
An addrList represents a list of network endpoint addresses. first returns the first address which satisfies strategy, or if
none do, then the first address of any kind. forResolve returns the most appropriate address in address for
a call to ResolveTCPAddr, ResolveUDPAddr, or ResolveIPAddr.
IPv4 is preferred, unless addr contains an IPv6 literal. partition divides an address list into two categories, using a
strategy function to assign a boolean label to each address.
The first address, and any with a matching label, are returned as
primaries, while addresses with the opposite label are returned
as fallbacks. For non-empty inputs, primaries is guaranteed to be
non-empty.
func filterAddrList(filter func(IPAddr) bool, ips []IPAddr, inetaddr func(IPAddr) Addr, originalAddr string) (addrList, error)
func (*Resolver).internetAddrList(ctx context.Context, net, addr string) (addrList, error)
func (*Resolver).resolveAddrList(ctx context.Context, op, network, addr string, hint Addr) (addrList, error)
An addrPortUDPAddr is a netip.AddrPort-based UDP address that satisfies the Addr interface.AddrPortnetip.AddrPortAddrPort.ipnetip.AddrAddrPort.portuint16 Addr returns p's IP address. AppendTo appends a text encoding of p,
as generated by MarshalText,
to b and returns the extended buffer. IsValid reports whether p.Addr() is valid.
All ports are valid, including zero. MarshalBinary implements the encoding.BinaryMarshaler interface.
It returns Addr.MarshalBinary with an additional two bytes appended
containing the port in little-endian. MarshalText implements the encoding.TextMarshaler interface. The
encoding is the same as returned by String, with one exception: if
p.Addr() is the zero Addr, the encoding is the empty string.( addrPortUDPAddr) Network() string Port returns p's port.( addrPortUDPAddr) String() string UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
It expects data in the form generated by MarshalBinary. UnmarshalText implements the encoding.TextUnmarshaler
interface. The AddrPort is expected in a form
generated by MarshalText or accepted by ParseAddrPort.
addrPortUDPAddr : Addr
addrPortUDPAddr : encoding.BinaryMarshaler
*addrPortUDPAddr : encoding.BinaryUnmarshaler
addrPortUDPAddr : encoding.TextMarshaler
*addrPortUDPAddr : encoding.TextUnmarshaler
addrPortUDPAddr : fmt.Stringer
addrPortUDPAddr : context.stringer
*addrPortUDPAddr : crypto/hmac.marshalable
addrPortUDPAddr : runtime.stringer
buffersWriter is the interface implemented by Conns that support a
"writev"-like batch write optimization.
writeBuffers should fully consume and write all chunks from the
provided Buffers, else it should report a non-nil error.( buffersWriter) writeBuffers(*Buffers) (int64, error)
*IPConn
*TCPConn
*UDPConn
*UnixConn
*conn
*netFD
byPref implements sort.Interface to sort MX records by preference( byPref) Len() int( byPref) Less(i, j int) bool( byPref) Swap(i, j int) sort reorders MX records as specified in RFC 5321.
byPref : sort.Interface
byPriorityWeight sorts SRV records by ascending priority and weight.( byPriorityWeight) Len() int( byPriorityWeight) Less(i, j int) bool( byPriorityWeight) Swap(i, j int) shuffleByWeight shuffles SRV records by weight using the algorithm
described in RFC 2782. sort reorders SRV records as specified in RFC 2782.
byPriorityWeight : sort.Interface
addrAttr[]ipAttr // addrs to sortsrcAttr[]ipAttr // or not valid addr if unreachable(*byRFC6724) Len() int Less reports whether i is a better destination address for this
host than j.
The algorithm and variable names comes from RFC 6724 section 6.(*byRFC6724) Swap(i, j int)
*byRFC6724 : sort.Interface
canceledError lets us return the same error string we have always
returned, while still being Is context.Canceled.( canceledError) Error() string( canceledError) Is(err error) bool
canceledError : error
var errCanceled
conf is used to determine name resolution configuration. // from GODEBUG // copy of runtime.GOOS, used for testing // assume /etc/mdns.allow exists, for testing // prefer cgo approach, based on build tag and GODEBUG // prefer go approach, based on build tag and GODEBUG // if no explicit preference, use cgo addrLookupOrder determines which strategy to use to resolve addresses.
The provided Resolver is optional. nil means to not consider its options.
It also returns dnsConfig when it was used to determine the lookup order. hostLookupOrder determines which strategy to use to resolve hostname.
The provided Resolver is optional. nil means to not consider its options.
It also returns dnsConfig when it was used to determine the lookup order.(*conf) lookupOrder(r *Resolver, hostname string) (ret hostLookupOrder, dnsConf *dnsConfig) mustUseGoResolver reports whether a DNS lookup of any sort is
required to use the go resolver. The provided Resolver is optional.
This will report true if the cgo resolver is not available.
func systemConf() *conf
var confVal *conf
fd*netFD Close closes the connection. File returns a copy of the underlying os.File.
It is the caller's responsibility to close f when finished.
Closing c does not affect f, and closing f does not affect c.
The returned os.File's file descriptor is different from the connection's.
Attempting to change properties of the original using this duplicate
may or may not have the desired effect. LocalAddr returns the local network address.
The Addr returned is shared by all invocations of LocalAddr, so
do not modify it. Read implements the Conn Read method. RemoteAddr returns the remote network address.
The Addr returned is shared by all invocations of RemoteAddr, so
do not modify it. SetDeadline implements the Conn SetDeadline method. SetReadBuffer sets the size of the operating system's
receive buffer associated with the connection. SetReadDeadline implements the Conn SetReadDeadline method. SetWriteBuffer sets the size of the operating system's
transmit buffer associated with the connection. SetWriteDeadline implements the Conn SetWriteDeadline method. Write implements the Conn Write method.(*conn) ok() bool(*conn) writeBuffers(v *Buffers) (int64, error)
*conn : Conn
*conn : internal/bisect.Writer
*conn : io.Closer
*conn : io.ReadCloser
*conn : io.Reader
*conn : io.ReadWriteCloser
*conn : io.ReadWriter
*conn : io.WriteCloser
*conn : io.Writer
*conn : buffersWriter
*conn : crypto/tls.transcriptHash
// guards followingipv4Enabledboolipv4MappedIPv6Enabledboolipv6Enabledbool done indicates whether the action has been performed.
It is first in the struct because it is used in the hot path.
The hot path is inlined at every call site.
Placing done first allows more compact instructions on some architectures (amd64/386),
and fewer instructions (to calculate offset) on other architectures.Once.msync.Mutex Do calls the function f if and only if Do is being called for the
first time for this instance of Once. In other words, given
var once Once
if once.Do(f) is called multiple times, only the first call will invoke f,
even if f has a different value in each invocation. A new instance of
Once is required for each function to execute.
Do is intended for initialization that must be run exactly once. Since f
is niladic, it may be necessary to use a function literal to capture the
arguments to a function to be invoked by Do:
config.once.Do(func() { config.init(filename) })
Because no call to Do returns until the one call to f returns, if f causes
Do to be called, it will deadlock.
If f panics, Do considers it to have returned; future calls of Do return
without calling f.(*ipStackCapabilities) doSlow(f func()) probe probes IPv4, IPv6 and IPv4-mapped IPv6 communication
capabilities which are controlled by the IPV6_V6ONLY socket option
and kernel configuration.
Should we try to use the IPv4 socket interface if we're only
dealing with IPv4 sockets? As long as the host system understands
IPv4-mapped IPv6, it's okay to pass IPv4-mapped IPv6 addresses to
the IPv6 interface. That simplifies our code and is most
general. Unfortunately, we need to run on kernels built without
IPv6 support too. So probe the kernel to figure it out.
var ipStackCaps
An ipv6ZoneCache represents a cache holding partial network
interface information. It is used for reducing the cost of IPv6
addressing scope zone resolution.
Multiple names sharing the index are managed by first-come
first-served basis for consistency. // guard the following // last time routing information was fetched // number of pending readers // semaphore for readers to wait for completing writers // number of departing readers // held if there are pending writers // semaphore for writers to wait for completing readers // interface name to its index // interface index to its name Lock locks rw for writing.
If the lock is already locked for reading or writing,
Lock blocks until the lock is available. 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 Lock and Unlock methods by calling rw.RLock and rw.RUnlock. RUnlock undoes a single 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. 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 RLock (Lock) a RWMutex and then
arrange for another goroutine to RUnlock (Unlock) it.(*ipv6ZoneCache) index(name string) int(*ipv6ZoneCache) name(index int) string(*ipv6ZoneCache) rUnlockSlow(r int32) update refreshes the network interface information if the cache was last
updated more than 1 minute ago, or if force is set. It reports whether the
cache was updated.
*ipv6ZoneCache : sync.Locker
var zoneCache
nssConf represents the state of the machine's /etc/nsswitch.conf file. // any error encountered opening or parsing the file // time of nsswitch.conf modification // keyed by database (e.g. "hosts")
func getSystemNSS() *nssConf
func parseNSSConf(f *file) *nssConf
func parseNSSConfFile(file string) *nssConf
nssCriterion is the parsed structure of one of the criteria in brackets
after an NSS source name. // e.g. "return", "continue" (lowercase) // if "!" was present // e.g. "success", "unavail" (lowercase) standardStatusAction reports whether c is equivalent to not
specifying the criterion at all. last is whether this criteria is the
last in the list.
func parseCriteria(x string) (c []nssCriterion, err error)
criteria[]nssCriterion // e.g. "compat", "files", "mdns4_minimal" standardCriteria reports all specified criteria have the default
status actions.
ch is used as a semaphore that only allows one lookup at a
time to recheck nsswitch.conf // guards lastChecked and modTime // guards init of nsswitchConfig // last time nsswitch.conf was checked // protects nssConfnssConf*nssConf(*nsswitchConfig) acquireSema() init initializes conf and is only called via conf.initOnce.(*nsswitchConfig) releaseSema()(*nsswitchConfig) tryAcquireSema() bool tryUpdate tries to update conf.
var nssConfig
onlyValuesCtx is a context that uses an underlying context
for value lookup if the underlying context hasn't yet expired.Contextcontext.ContextlookupValuescontext.Context Deadline returns the time when work done on behalf of this context
should be canceled. Deadline returns ok==false when no deadline is
set. Successive calls to Deadline return the same results. Done returns a channel that's closed when work done on behalf of this
context should be canceled. Done may return nil if this context can
never be canceled. Successive calls to Done return the same value.
The close of the Done channel may happen asynchronously,
after the cancel function returns.
WithCancel arranges for Done to be closed when cancel is called;
WithDeadline arranges for Done to be closed when the deadline
expires; WithTimeout arranges for Done to be closed when the timeout
elapses.
Done is provided for use in select statements:
// Stream generates values with DoSomething and sends them to out
// until DoSomething returns an error or ctx.Done is closed.
func Stream(ctx context.Context, out chan<- Value) error {
for {
v, err := DoSomething(ctx)
if err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case out <- v:
}
}
}
See https://blog.golang.org/pipelines for more examples of how to use
a Done channel for cancellation. If Done is not yet closed, Err returns nil.
If Done is closed, Err returns a non-nil error explaining why:
Canceled if the context was canceled
or DeadlineExceeded if the context's deadline passed.
After Err returns a non-nil error, successive calls to Err return the same error. Value performs a lookup if the original context hasn't expired.
*onlyValuesCtx : context.Context
pipeDeadline is an abstraction for handling timeouts. // Must be non-nil // Guards timer and canceltimer*time.Timer set sets the point in time when the deadline will time out.
A timeout event is signaled by closing the channel returned by waiter.
Once a timeout has occurred, the deadline can be refreshed by specifying a
t value in the future.
A zero value for t prevents timeout. wait returns a channel that is closed when the deadline is exceeded.
func makePipeDeadline() pipeDeadline
Classify returns the policyTableEntry of the entry with the longest
matching prefix that contains ip.
The table t must be sorted from largest mask size to smallest.
var rfc6724policyTable
fd*netFD(*rawConn) Control(f func(uintptr)) error PollFD returns the poll.FD of the underlying connection.
Other packages in std that also import internal/poll (such as os)
can use a type assertion to access this extension method so that
they can pass the *poll.FD to functions like poll.Splice.
PollFD is not intended for use outside the standard library.(*rawConn) Read(f func(uintptr) bool) error(*rawConn) Write(f func(uintptr) bool) error(*rawConn) ok() bool
*rawConn : syscall.RawConn
func newRawConn(fd *netFD) (*rawConn, error)
rawConnrawConnrawConn.fd*netFD(*rawListener) Control(f func(uintptr)) error PollFD returns the poll.FD of the underlying connection.
Other packages in std that also import internal/poll (such as os)
can use a type assertion to access this extension method so that
they can pass the *poll.FD to functions like poll.Splice.
PollFD is not intended for use outside the standard library.(*rawListener) Read(func(uintptr) bool) error(*rawListener) Write(func(uintptr) bool) error(*rawListener) ok() bool
*rawListener : syscall.RawConn
func newRawListener(fd *netFD) (*rawListener, error)
A resolverConfig represents a DNS stub resolver configuration. ch is used as a semaphore that only allows one lookup at a
time to recheck resolv.conf. // guards lastChecked and modTime // parsed resolv.conf structure used in lookups // guards init of resolverConfig // last time resolv.conf was checked init initializes conf and is only called via conf.initOnce.(*resolverConfig) releaseSema()(*resolverConfig) tryAcquireSema() bool tryUpdate tries to update conf with the named resolv.conf file.
The name variable only exists for testing. It is otherwise always
"/etc/resolv.conf".
var resolvConf
sysDialer contains a Dial's parameters and configuration.DialerDialer Cancel is an optional channel whose closure indicates that
the dial should be canceled. Not all types of dials support
cancellation.
Deprecated: Use DialContext instead. If Control is not nil, it is called after creating the network
connection but before actually dialing.
Network and address parameters passed to Control function are not
necessarily the ones passed to Dial. For example, passing "tcp" to Dial
will cause the Control function to be called with "tcp4" or "tcp6".
Control is ignored if ControlContext is not nil. If ControlContext is not nil, it is called after creating the network
connection but before actually dialing.
Network and address parameters passed to ControlContext function are not
necessarily the ones passed to Dial. For example, passing "tcp" to Dial
will cause the ControlContext function to be called with "tcp4" or "tcp6".
If ControlContext is not nil, Control is ignored. 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. DualStack previously enabled RFC 6555 Fast Fallback
support, also known as "Happy Eyeballs", in which IPv4 is
tried soon if IPv6 appears to be misconfigured and
hanging.
Deprecated: Fast Fallback is enabled by default. To
disable, set FallbackDelay to a negative value. FallbackDelay specifies the length of time to wait before
spawning a RFC 6555 Fast Fallback connection. That is, this
is the amount of time to wait for IPv6 to succeed before
assuming that IPv6 is misconfigured and falling back to
IPv4.
If zero, a default delay of 300ms is used.
A negative value disables Fast Fallback support. 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. 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. Resolver optionally specifies an alternate resolver to use. 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.addressstring If mptcpStatus is set to a value allowing Multipath TCP (MPTCP) to be
used, any call to Dial with "tcp(4|6)" as network will use MPTCP if
supported by the operating system.networkstringtestHookDialTCPfunc(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, 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. 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. MultipathTCP reports whether MPTCP will be used.
This method doesn't check if MPTCP is supported by the operating
system or not. SetMultipathTCP directs the Dial methods to use, or not use, MPTCP,
if supported by the operating system. This method overrides the
system default and the GODEBUG=multipathtcp=... setting if any.
If MPTCP is not available on the host or not supported by the server,
the Dial methods will fall back to TCP. deadline returns the earliest of:
- now+Timeout
- d.Deadline
- the context's deadline
Or zero, if none of Timeout, Deadline, or context's deadline is set.(*sysDialer) dialIP(ctx context.Context, laddr, raddr *IPAddr) (*IPConn, error)(*sysDialer) dialMPTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) dialParallel races two copies of dialSerial, giving the first a
head start. It returns the first established connection and
closes the others. Otherwise it returns an error from the first
primary address. dialSerial connects to a list of addresses in sequence, returning
either the first successful connection, or the first error. dialSingle attempts to establish and returns a single connection to
the destination address.(*sysDialer) dialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error)(*sysDialer) dialUDP(ctx context.Context, laddr, raddr *UDPAddr) (*UDPConn, error)(*sysDialer) dialUnix(ctx context.Context, laddr, raddr *UnixAddr) (*UnixConn, error)(*sysDialer) doDialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error)(*sysDialer) doDialTCPProto(ctx context.Context, laddr, raddr *TCPAddr, proto int) (*TCPConn, error)(*sysDialer) dualStack() bool(*sysDialer) fallbackDelay() time.Duration(*sysDialer) resolver() *Resolver
*sysDialer : golang.org/x/net/proxy.ContextDialer
*sysDialer : golang.org/x/net/proxy.Dialer
sysListener contains a Listen's parameters and configuration.ListenConfigListenConfig 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". 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.addressstring If mptcpStatus is set to a value allowing Multipath TCP (MPTCP) to be
used, any call to Listen with "tcp(4|6)" as network will use MPTCP if
supported by the operating system.networkstring Listen announces on the local network address.
See func Listen for a description of the network and address
parameters. ListenPacket announces on the local network address.
See func ListenPacket for a description of the network and address
parameters. MultipathTCP reports whether MPTCP will be used.
This method doesn't check if MPTCP is supported by the operating
system or not. SetMultipathTCP directs the Listen method to use, or not use, MPTCP,
if supported by the operating system. This method overrides the
system default and the GODEBUG=multipathtcp=... setting if any.
If MPTCP is not available on the host or not supported by the client,
the Listen method will fall back to TCP.(*sysListener) listenIP(ctx context.Context, laddr *IPAddr) (*IPConn, error)(*sysListener) listenMPTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error)(*sysListener) listenMulticastUDP(ctx context.Context, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)(*sysListener) listenTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error)(*sysListener) listenTCPProto(ctx context.Context, laddr *TCPAddr, proto int) (*TCPListener, error)(*sysListener) listenUDP(ctx context.Context, laddr *UDPAddr) (*UDPConn, error)(*sysListener) listenUnix(ctx context.Context, laddr *UnixAddr) (*UnixListener, error)(*sysListener) listenUnixgram(ctx context.Context, laddr *UnixAddr) (*UnixConn, error)
Package-Level Functions (total 275, in which 45 are exported)
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.
Dial connects to the address on the named network.
Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only),
"udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4"
(IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and
"unixpacket".
For TCP and UDP networks, the address has the form "host:port".
The host must be a literal IP address, or a host name that can be
resolved to IP addresses.
The port must be a literal port number or a service name.
If the host is a literal IPv6 address it must be enclosed in square
brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80".
The zone specifies the scope of the literal IPv6 address as defined
in RFC 4007.
The functions JoinHostPort and SplitHostPort manipulate a pair of
host and port in this form.
When using TCP, and the host resolves to multiple IP addresses,
Dial will try each IP address in order until one succeeds.
Examples:
Dial("tcp", "golang.org:http")
Dial("tcp", "192.0.2.1:http")
Dial("tcp", "198.51.100.1:80")
Dial("udp", "[2001:db8::1]:domain")
Dial("udp", "[fe80::1%lo0]:53")
Dial("tcp", ":80")
For IP networks, the network must be "ip", "ip4" or "ip6" followed
by a colon and a literal protocol number or a protocol name, and
the address has the form "host". The host must be a literal IP
address or a literal IPv6 address with zone.
It depends on each operating system how the operating system
behaves with a non-well known protocol number such as "0" or "255".
Examples:
Dial("ip4:1", "192.0.2.1")
Dial("ip6:ipv6-icmp", "2001:db8::1")
Dial("ip6:58", "fe80::1%lo0")
For TCP, UDP and IP networks, if the host is empty or a literal
unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for
TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is
assumed.
For Unix networks, the address must be a file system path.
DialIP acts like Dial for IP networks.
The network must be an IP 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.
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.
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.
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.
DialUnix acts like Dial for Unix networks.
The network must be a Unix network name; see func Dial for details.
If laddr is non-nil, it is used as the local address for the
connection.
FileConn returns a copy of the network connection corresponding to
the open file f.
It is the caller's responsibility to close f when finished.
Closing c does not affect f, and closing f does not affect c.
FileListener returns a copy of the network listener corresponding
to the open file f.
It is the caller's responsibility to close ln when finished.
Closing ln does not affect f, and closing f does not affect ln.
FilePacketConn returns a copy of the packet network connection
corresponding to the open file f.
It is the caller's responsibility to close f when finished.
Closing c does not affect f, and closing f does not affect c.
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.
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.
InterfaceByName returns the interface specified by name.
Interfaces returns a list of the system's network interfaces.
IPv4 returns the IP address (in 16-byte form) of the
IPv4 address a.b.c.d.
IPv4Mask returns the IP mask (in 4-byte form) of the
IPv4 mask a.b.c.d.
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.
Listen announces on the local network address.
The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket".
For TCP networks, if the host in the address parameter is empty or
a literal unspecified IP address, Listen listens on all available
unicast and anycast IP addresses of the local system.
To only use IPv4, use network "tcp4".
The address can use a host name, but this is not recommended,
because it will create a listener for at most one of the host's IP
addresses.
If the port in the address parameter is empty or "0", as in
"127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
The Addr method of Listener can be used to discover the chosen
port.
See func Dial for a description of the network and address
parameters.
Listen uses context.Background internally; to specify the context, use
ListenConfig.Listen.
ListenIP acts like ListenPacket for IP networks.
The network must be an IP network name; see func Dial for details.
If the IP field of laddr is nil or an unspecified IP address,
ListenIP listens on all available IP addresses of the local system
except multicast IP addresses.
ListenMulticastUDP acts like ListenPacket for UDP networks but
takes a group address on a specific network interface.
The network must be a UDP network name; see func Dial for details.
ListenMulticastUDP listens on all available IP addresses of the
local system including the group, multicast IP address.
If ifi is nil, ListenMulticastUDP uses the system-assigned
multicast interface, although this is not recommended because the
assignment depends on platforms and sometimes it might require
routing configuration.
If the Port field of gaddr is 0, a port number is automatically
chosen.
ListenMulticastUDP is just for convenience of simple, small
applications. There are golang.org/x/net/ipv4 and
golang.org/x/net/ipv6 packages for general purpose uses.
Note that ListenMulticastUDP will set the IP_MULTICAST_LOOP socket option
to 0 under IPPROTO_IP, to disable loopback of multicast packets.
ListenPacket announces on the local network address.
The network must be "udp", "udp4", "udp6", "unixgram", or an IP
transport. The IP transports are "ip", "ip4", or "ip6" followed by
a colon and a literal protocol number or a protocol name, as in
"ip:1" or "ip:icmp".
For UDP and IP networks, if the host in the address parameter is
empty or a literal unspecified IP address, ListenPacket listens on
all available IP addresses of the local system except multicast IP
addresses.
To only use IPv4, use network "udp4" or "ip4:proto".
The address can use a host name, but this is not recommended,
because it will create a listener for at most one of the host's IP
addresses.
If the port in the address parameter is empty or "0", as in
"127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
The LocalAddr method of PacketConn can be used to discover the
chosen port.
See func Dial for a description of the network and address
parameters.
ListenPacket uses context.Background internally; to specify the context, use
ListenConfig.ListenPacket.
ListenTCP acts like Listen for TCP networks.
The network must be a TCP network name; see func Dial for details.
If the IP field of laddr is nil or an unspecified IP address,
ListenTCP listens on all available unicast and anycast IP addresses
of the local system.
If the Port field of laddr is 0, a port number is automatically
chosen.
ListenUDP acts like ListenPacket for UDP networks.
The network must be a UDP network name; see func Dial for details.
If the IP field of laddr is nil or an unspecified IP address,
ListenUDP listens on all available IP addresses of the local system
except multicast IP addresses.
If the Port field of laddr is 0, a port number is automatically
chosen.
ListenUnix acts like Listen for Unix networks.
The network must be "unix" or "unixpacket".
ListenUnixgram acts like ListenPacket for Unix networks.
The network must be "unixgram".
LookupAddr performs a reverse lookup for the given address, returning a list
of names mapping to that address.
The returned names are validated to be properly formatted presentation-format
domain names. If the response contains invalid names, those records are filtered
out and an error will be returned alongside the remaining results, if any.
When using the host C library resolver, at most one result will be
returned. To bypass the host resolver, use a custom Resolver.
LookupAddr uses context.Background internally; to specify the context, use
Resolver.LookupAddr.
LookupCNAME returns the canonical name for the given host.
Callers that do not care about the canonical name can call
LookupHost or LookupIP directly; both take care of resolving
the canonical name as part of the lookup.
A canonical name is the final name after following zero
or more CNAME records.
LookupCNAME does not return an error if host does not
contain DNS "CNAME" records, as long as host resolves to
address records.
The returned canonical name is validated to be a properly
formatted presentation-format domain name.
LookupCNAME uses context.Background internally; to specify the context, use
Resolver.LookupCNAME.
LookupHost looks up the given host using the local resolver.
It returns a slice of that host's addresses.
LookupHost uses context.Background internally; to specify the context, use
Resolver.LookupHost.
LookupIP looks up host using the local resolver.
It returns a slice of that host's IPv4 and IPv6 addresses.
LookupMX returns the DNS MX records for the given domain name sorted by preference.
The returned mail server names are validated to be properly
formatted presentation-format domain names. If the response contains
invalid names, those records are filtered out and an error
will be returned alongside the remaining results, if any.
LookupMX uses context.Background internally; to specify the context, use
Resolver.LookupMX.
LookupNS returns the DNS NS records for the given domain name.
The returned name server names are validated to be properly
formatted presentation-format domain names. If the response contains
invalid names, those records are filtered out and an error
will be returned alongside the remaining results, if any.
LookupNS uses context.Background internally; to specify the context, use
Resolver.LookupNS.
LookupPort looks up the port for the given network and service.
LookupPort uses context.Background internally; to specify the context, use
Resolver.LookupPort.
LookupSRV tries to resolve an SRV query of the given service,
protocol, and domain name. The proto is "tcp" or "udp".
The returned records are sorted by priority and randomized
by weight within a priority.
LookupSRV constructs the DNS name to look up following RFC 2782.
That is, it looks up _service._proto.name. To accommodate services
publishing SRV records under non-standard names, if both service
and proto are empty strings, LookupSRV looks up name directly.
The returned service names are validated to be properly
formatted presentation-format domain names. If the response contains
invalid names, those records are filtered out and an error
will be returned alongside the remaining results, if any.
LookupTXT returns the DNS TXT records for the given domain name.
LookupTXT uses context.Background internally; to specify the context, use
Resolver.LookupTXT.
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.
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.
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
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.
ResolveIPAddr returns an address of IP end point.
The network must be an IP network name.
If the host in the address parameter is not a literal IP address,
ResolveIPAddr resolves the address to an address of IP end point.
Otherwise, it parses the address as a literal IP address.
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.
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.
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.
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.
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.
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.
UDPAddrFromAddrPort returns addr as a UDPAddr. If addr.IsValid() is false,
then the returned UDPAddr will contain a nil IP field, indicating an
address family-agnostic unspecified address.
absDomainName returns an absolute domain name which ends with a
trailing dot to match pure Go reverse resolver and all other lookup
routines.
See golang.org/issue/12189.
But we don't want to add dots for local names from /etc/hosts.
It's hard to tell so we settle on the heuristic that names without dots
(like "localhost" or "myhost") do not get trailing dots, but any other
names do.
Convert i to a hexadecimal string. Leading zeros are not printed.
avoidDNS reports whether this is a hostname for which we should not
use DNS. Currently this includes only .onion, per RFC 7686. See
golang.org/issue/13705. Does not cover .local names (RFC 6762),
see golang.org/issue/16739.
commonPrefixLen reports the length of the longest prefix (looking
at the most significant, or leftmost, bits) that the
two addresses have in common, up to the length of a's prefix (i.e.,
the portion of the address not including the interface ID).
If a or b is an IPv4 address as an IPv6 address, the IPv4 addresses
are compared (with max common prefix length of 32).
If a and b are different IP versions, 0 is returned.
See https://tools.ietf.org/html/rfc6724#section-2.2
concurrentThreadsLimit returns the number of threads we permit to
run concurrently doing DNS lookups via cgo. A DNS lookup may use a
file descriptor so we limit this to less than the number of
permitted open files. On some systems, notably Darwin, if
getaddrinfo is unable to open a file descriptor it simply returns
EAI_NONAME rather than a useful error. Limiting the number of
concurrent getaddrinfo calls to less than the permitted number of
file descriptors makes that error less likely. We don't bother to
apply the same limit to DNS lookups run directly from Go, because
there we will return a meaningful "too many open files" error.
Type Parameters:
T: any doBlockingWithCtx executes a blocking function in a separate goroutine when the provided
context is cancellable. It is intended for use with calls that don't support context
cancellation (cgo, syscalls). blocking func may still be running after this function finishes.
Decimal to integer.
Returns number, characters consumed, success.
favoriteAddrFamily returns the appropriate address family for the
given network, laddr, raddr and mode.
If mode indicates "listen" and laddr is a wildcard, we assume that
the user wants to make a passive-open connection with a wildcard
address family, both AF_INET and AF_INET6, and a wildcard address
like the following:
- A listen for a wildcard communication domain, "tcp" or
"udp", with a wildcard address: If the platform supports
both IPv6 and IPv4-mapped IPv6 communication capabilities,
or does not support IPv4, we use a dual stack, AF_INET6 and
IPV6_V6ONLY=0, wildcard address listen. The dual stack
wildcard address listen may fall back to an IPv6-only,
AF_INET6 and IPV6_V6ONLY=1, wildcard address listen.
Otherwise we prefer an IPv4-only, AF_INET, wildcard address
listen.
- A listen for a wildcard communication domain, "tcp" or
"udp", with an IPv4 wildcard address: same as above.
- A listen for a wildcard communication domain, "tcp" or
"udp", with an IPv6 wildcard address: same as above.
- A listen for an IPv4 communication domain, "tcp4" or "udp4",
with an IPv4 wildcard address: We use an IPv4-only, AF_INET,
wildcard address listen.
- A listen for an IPv6 communication domain, "tcp6" or "udp6",
with an IPv6 wildcard address: We use an IPv6-only, AF_INET6
and IPV6_V6ONLY=1, wildcard address listen.
Otherwise guess: If the addresses are IPv4 then returns AF_INET,
or else returns AF_INET6. It also returns a boolean value what
designates IPV6_V6ONLY option.
Note that the latest DragonFly BSD and OpenBSD kernels allow
neither "net.inet6.ip6.v6only=1" change nor IPPROTO_IPV6 level
IPV6_V6ONLY socket option setting.
filterAddrList applies a filter to a list of IP addresses,
yielding a list of Addr objects. Known filters are nil, ipv4only,
and ipv6only. It returns every address when the filter is nil.
The result contains at least one address when error is nil.
foreachField runs fn on each non-empty run of non-space bytes in x.
It returns the first non-nil error returned by fn.
Fallback implementation of io.ReaderFrom's ReadFrom, when sendfile isn't
applicable.
goDebugNetDNS parses the value of the GODEBUG "netdns" value.
The netdns value can be of the form:
1 // debug level 1
2 // debug level 2
cgo // use cgo for DNS lookups
go // use go for DNS lookups
cgo+1 // use cgo for DNS lookups + debug level 1
1+cgo // same
cgo+2 // same, but debug level 2
etc.
lookup entries from /etc/hosts
goLookupPort is the native Go implementation of LookupPort.
goosPreferCgo reports whether the GOOS value passed in prefers
the cgo resolver.
hasFallenBack reports whether the MPTCP connection has fallen back to "plain"
TCP.
A connection can fallback to TCP for different reasons, e.g. the other peer
doesn't support it, a middle box "accidentally" drops the option, etc.
If the MPTCP protocol has not been requested when creating the socket, this
method will return true: MPTCP is not being used.
Kernel >= 5.16 returns EOPNOTSUPP/ENOPROTOOPT in case of fallback.
Older kernels will always return them even if MPTCP is used: not usable.
isDomainName checks if a string is a presentation-format domain name
(currently restricted to hostname-compatible "preferred name" LDH labels and
SRV-like "underscore labels"; see golang.org/issue/12421).
isGateway reports whether h should be considered a "gateway"
name for the myhostname NSS module.
isIPv4 reports whether addr contains an IPv4 address.
isLocalhost reports whether h should be considered a "localhost"
name for the myhostname NSS module.
isNotIPv4 reports whether addr does not contain an IPv4 address.
isOutbound reports whether h should be considered a "outbound"
name for the myhostname NSS module.
isSpace reports whether b is an ASCII space character.
isUsingMPTCPProto reports whether the socket protocol is MPTCP.
Compared to hasFallenBack method, here only the socket protocol being used is
checked: it can be MPTCP but it doesn't mean MPTCP is used on the wire, maybe
a fallback to TCP has been done.
isUsingMultipathTCP reports whether MPTCP is still being used.
Please look at the description of hasFallenBack (kernel >=5.16) and
isUsingMPTCPProto methods for more details about what is being checked here.
mapErr maps from the context errors to the historical internal net
error values.
Linux stores the backlog as:
- uint16 in kernel version < 4.1,
- uint32 in kernel version >= 4.1
Truncate number to avoid wrapping.
See issue 5030 and 41470.
parsePort parses service as a decimal integer and returns the
corresponding value as port. It is the caller's responsibility to
parse service as a non-decimal integer when needsLookup is true.
Some system resolvers will return a valid port number when given a number
over 65536 (see https://golang.org/issues/11715). Alas, the parser
can't bail early on numbers > 65536. Therefore reasonably large/small
numbers are parsed in full and rejected if invalid.
removeComment returns line, removing any '#' byte and any following
bytes.
resSearch will make a call to the 'res_nsearch' routine in the C library
and parse the output as a slice of DNS resources.
reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
address addr suitable for rDNS (PTR) record lookup or an error if it fails
to parse the IP address.
roundDurationUp rounds d to the next multiple of to.
sendFile copies the contents of r to c using the sendfile
system call to minimize copies.
if handled == true, sendFile returns the number (potentially zero) of bytes
copied and any non-EOF error.
if handled == false, sendFile performed no work.
splice transfers data from r to c using the splice system call to minimize
copies from and to userspace. c must be a TCP connection. Currently, splice
is only enabled if r is a TCP or a stream-oriented Unix connection.
If splice returns handled == false, it has performed no work.
supportsIPv4 reports whether the platform supports IPv4 networking
functionality.
supportsIPv4map reports whether the platform supports mapping an
IPv4 address inside an IPv6 address at transport layer
protocols. See RFC 4291, RFC 4038 and RFC 3493.
supportsIPv6 reports whether the platform supports IPv6 networking
functionality.
withUnexpiredValuesPreserved returns a context.Context that only uses lookupCtx
for its values, otherwise it is never canceled and has no deadline.
If the lookup context expires, any looked up values will return nil.
See Issue 28600.
wrapSyscallError takes an error and a syscall name. If the error is
a syscall.Errno, it wraps it in an os.SyscallError using the syscall name.
Hexadecimal to integer.
Returns number, characters consumed, success.
xtoi2 converts the next two hex digits of s into a byte.
If s is longer than 2 bytes then the third byte must be e.
If the first two bytes of s are not hex digits or the third byte
does not match e, false is returned.
Package-Level Variables (total 95, in which 13 are exported)
DefaultResolver is the resolver used by the package-level Lookup
functions and by Dialers without a specified Resolver.
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).
errMalformedDNSRecordsDetail is the DNSError detail which is returned when a Resolver.Lookup...
method receives DNS records which contain invalid DNS names. This may be returned alongside
results which have had the malformed records filtered out.
errServerTemporarilyMisbehaving is like errServerMisbehaving, except
that when it gets translated to a DNSError, the IsTemporary field
gets set to true.
errTimeout exists to return the historical "i/o timeout" string
for context.DeadlineExceeded. See mapErr.
It is also used when Dialer.Deadline is exceeded.
error.Is(errTimeout, context.DeadlineExceeded) returns true.
TODO(iant): We could consider changing this to os.ErrDeadlineExceeded
in the future, if we make
errors.Is(os.ErrDeadlineExceeded, context.DeadlineExceeded)
return true.
protocols contains minimal mappings between internet protocol
names and numbers for platforms that don't have a complete list of
protocol numbers.
See https://www.iana.org/assignments/protocol-numbers
On Unix, this map is augmented by readProtocols via lookupProtocol.
RFC 6724 section 2.1.
Items are sorted by the size of their Prefix.Mask.Size,
services contains minimal mappings between services names and port
numbers for platforms that don't have a complete list of port numbers.
See https://www.iana.org/assignments/service-names-port-numbers
On Unix, this map is augmented by readServices via goLookupPort.
NOTE(rsc): In theory there are approximately balanced
arguments for and against including AI_ADDRCONFIG
in the flags (it includes IPv4 results only on IPv4 systems,
and similarly for IPv6), but in practice setting it causes
getaddrinfo to return the wrong canonical name on Linux.
So definitely leave it out.
cgoAvailable set to true to indicate that the cgo resolver
is available on this system.
For the moment, MultiPath TCP is not used by default
See go.dev/issue/56539
defaultTCPKeepAlive is a default constant value for TCPKeepAlive times
See go.dev/issue/31510
Maximum DNS packet size.
Value taken from https://dnsflagday.net/2020/.
These are roughly enough for the following:
Source Encoding Maximum length of single name entry
Unicast DNS ASCII or <=253 + a NUL terminator
Unicode in RFC 5892 252 * total number of labels + delimiters + a NUL terminator
Multicast DNS UTF-8 in RFC 5198 or <=253 + a NUL terminator
the same as unicast DNS ASCII <=253 + a NUL terminator
Local database various depends on implementation
maxPortBufSize is the longest reasonable name of a service
(non-numeric port).
Currently the longest known IANA-unregistered name is
"mobility-header", so we use that length, plus some slop in case
something longer is added in the future.
The value 0 is the system default, linked to defaultMPTCPEnabled
These are roughly enough for the following:
Source Encoding Maximum length of single name entry
Unicast DNS ASCII or <=253 + a NUL terminator
Unicode in RFC 5892 252 * total number of labels + delimiters + a NUL terminator
Multicast DNS UTF-8 in RFC 5198 or <=253 + a NUL terminator
the same as unicast DNS ASCII <=253 + a NUL terminator
Local database various depends on implementation
The pages are generated with Goldsv0.6.7. (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 @Go100and1 (reachable from the left QR code) to get the latest news of Golds.