Black Lives Matter. Support the Equal Justice Initiative.

Package net

Overview ▾

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 cgo resolver

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 Plan 9, the resolver always accesses /net/cs and /net/dns.

On Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery.

Index ▾

Constants
Variables
func Dial(network, address string) (Conn, error)
func DialIP(network string, laddr, raddr *IPAddr) (*IPConn, error)
func DialTCP(network string, laddr, raddr *TCPAddr) (*TCPConn, error)
func DialTimeout(network, address string, timeout time.Duration) (Conn, error)
func DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error)
func DialUnix(network string, laddr, raddr *UnixAddr) (*UnixConn, error)
func FileConn(f *os.File) (c Conn, err error)
func FileListener(f *os.File) (ln Listener, err error)
func FilePacketConn(f *os.File) (c PacketConn, err error)
func InterfaceAddrs() ([]Addr, error)
func InterfaceByIndex(index int) (*Interface, error)
func InterfaceByName(name string) (*Interface, error)
func Interfaces() ([]Interface, error)
func JoinHostPort(host, port string) string
func Listen(network, address string) (Listener, error)
func ListenIP(network string, laddr *IPAddr) (*IPConn, error)
func ListenMulticastUDP(network string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)
func ListenPacket(network, address string) (PacketConn, error)
func ListenTCP(network string, laddr *TCPAddr) (*TCPListener, error)
func ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error)
func ListenUnix(network string, laddr *UnixAddr) (*UnixListener, error)
func ListenUnixgram(network string, laddr *UnixAddr) (*UnixConn, error)
func LookupAddr(addr string) (names []string, err error)
func LookupCNAME(host string) (cname string, err error)
func LookupHost(host string) (addrs []string, err error)
func LookupIP(host string) ([]IP, error)
func LookupMX(name string) ([]*MX, error)
func LookupNS(name string) ([]*NS, error)
func LookupPort(network, service string) (port int, err error)
func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error)
func LookupTXT(name string) ([]string, error)
func ParseCIDR(s string) (IP, *IPNet, error)
func ParseMAC(s string) (hw HardwareAddr, err error)
func Pipe() (Conn, Conn)
func ResolveIPAddr(network, address string) (*IPAddr, error)
func ResolveTCPAddr(network, address string) (*TCPAddr, error)
func ResolveUDPAddr(network, address string) (*UDPAddr, error)
func ResolveUnixAddr(network, address string) (*UnixAddr, error)
func SplitHostPort(hostport string) (host, port string, err error)
func absDomainName(b []byte) string
func acquireThread()
func addrTable(ift []Interface, ifi *Interface, msgs []syscall.NetlinkMessage) ([]Addr, error)
func allFF(b []byte) bool
func appendHex(dst []byte, i uint32) []byte
func avoidDNS(name string) bool
func boolint(b bool) int
func cgoIPLookup(result chan<- ipLookupResult, network, name string)
func cgoLookupAddrPTR(addr string, sa *C.struct_sockaddr, salen C.socklen_t) (names []string, err error)
func cgoLookupCNAME(ctx context.Context, name string) (cname string, err error, completed bool)
func cgoLookupHost(ctx context.Context, name string) (hosts []string, err error, completed bool)
func cgoLookupIP(ctx context.Context, network, name string) (addrs []IPAddr, err error, completed bool)
func cgoLookupIPCNAME(network, name string) (addrs []IPAddr, cname string, err error)
func cgoLookupPTR(ctx context.Context, addr string) (names []string, err error, completed bool)
func cgoLookupPort(ctx context.Context, network, service string) (port int, err error, completed bool)
func cgoLookupServicePort(hints *C.struct_addrinfo, network, service string) (port int, err error)
func cgoNameinfoPTR(b []byte, sa *C.struct_sockaddr, salen C.socklen_t) (int, error)
func cgoPortLookup(result chan<- portLookupResult, hints *C.struct_addrinfo, network, service string)
func cgoReverseLookup(result chan<- reverseLookupResult, addr string, sa *C.struct_sockaddr, salen C.socklen_t)
func cgoSockaddr(ip IP, zone string) (*C.struct_sockaddr, C.socklen_t)
func cgoSockaddrInet4(ip IP) *C.struct_sockaddr
func cgoSockaddrInet6(ip IP, zone int) *C.struct_sockaddr
func checkHeader(p *dnsmessage.Parser, h dnsmessage.Header) error
func checkResponse(reqID uint16, reqQues dnsmessage.Question, respHdr dnsmessage.Header, respQues dnsmessage.Question) bool
func commonPrefixLen(a, b IP) (cpl int)
func concurrentThreadsLimit() int
func count(s string, b byte) int
func countAnyByte(s string, t string) int
func dnsDefaultSearch() []string
func dnsPacketRoundTrip(c Conn, id uint16, query dnsmessage.Question, b []byte) (dnsmessage.Parser, dnsmessage.Header, error)
func dnsStreamRoundTrip(c Conn, id uint16, query dnsmessage.Question, b []byte) (dnsmessage.Parser, dnsmessage.Header, error)
func dtoi(s string) (n int, i int, ok bool)
func dupSocket(f *os.File) (int, error)
func ensureRooted(s string) string
func equalASCIIName(x, y dnsmessage.Name) bool
func fastrand() uint32
func favoriteAddrFamily(network string, laddr, raddr sockaddr, mode string) (family int, ipv6only bool)
func fileConn(f *os.File) (Conn, error)
func fileListener(f *os.File) (Listener, error)
func filePacketConn(f *os.File) (PacketConn, error)
func filterAddrList(filter func(IPAddr) bool, ips []IPAddr, inetaddr func(IPAddr) Addr, originalAddr string) (addrList, error)
func foreachField(x []byte, fn func(field []byte) error) error
func foreachLine(x []byte, fn func(line []byte) error) error
func genericReadFrom(w io.Writer, r io.Reader) (n int64, err error)
func getFields(s string) []string
func goDebugNetDNS() (dnsMode string, debugLevel int)
func goDebugString(key string) string
func goLookupPort(network, service string) (port int, err error)
func hasPrefix(s, prefix string) bool
func hexString(b []byte) string
func init()
func initConfVal()
func interfaceAddrTable(ifi *Interface) ([]Addr, error)
func interfaceByIndex(ift []Interface, index int) (*Interface, error)
func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error)
func interfaceTable(ifindex int) ([]Interface, error)
func interfaceToIPv4Addr(ifi *Interface) (IP, error)
func internetSocket(ctx context.Context, net string, laddr, raddr sockaddr, sotype, proto int, mode string, ctrlFn func(string, string, syscall.RawConn) error) (fd *netFD, err error)
func ipAddrsEface(addrs []IPAddr) []interface{}
func ipEmptyString(ip IP) string
func ipToSockaddr(family int, ip IP, port int, zone string) (syscall.Sockaddr, error)
func ipVersion(network string) byte
func ipv4AddrToInterface(ip IP) (*Interface, error)
func ipv4only(addr IPAddr) bool
func ipv6only(addr IPAddr) bool
func isClosedChan(c <-chan struct{}) bool
func isConnError(err error) bool
func isDomainName(s string) bool
func isGateway(h string) bool
func isIPv4(addr Addr) bool
func isLocalhost(h string) bool
func isNotIPv4(addr Addr) bool
func isSpace(b byte) bool
func isZeros(p IP) bool
func itoa(val int) string
func joinIPv4Group(fd *netFD, ifi *Interface, ip IP) error
func joinIPv6Group(fd *netFD, ifi *Interface, ip IP) error
func kernelVersion() (major int, minor int)
func last(s string, b byte) int
func listenIPv4MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error
func listenIPv6MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error
func listenerBacklog() int
func lookupIPReturn(addrsi interface{}, err error, shared bool) ([]IPAddr, error)
func lookupPortMap(network, service string) (port int, error error)
func lookupProtocol(_ context.Context, name string) (int, error)
func lookupProtocolMap(name string) (int, error)
func lookupStaticAddr(addr string) []string
func lookupStaticHost(host string) []string
func lowerASCII(b byte) byte
func lowerASCIIBytes(x []byte)
func mapErr(err error) error
func maxAckBacklog(n int) int
func maxListenerBacklog() int
func minNonzeroTime(a, b time.Time) time.Time
func networkNumberAndMask(n *IPNet) (ip IP, m IPMask)
func newFD(sysfd, family, sotype int, net string) (*netFD, error)
func newFileFD(f *os.File) (*netFD, error)
func newRawConn(fd *netFD) (*rawConn, error)
func newRawListener(fd *netFD) (*rawListener, error)
func newRequest(q dnsmessage.Question) (id uint16, udpReq, tcpReq []byte, err error)
func open(name string) (*file, error)
func parseCriteria(x []byte) (c []nssCriterion, err error)
func parseLiteralIP(addr string) string
func parseNetwork(ctx context.Context, network string, needsProto bool) (afnet string, proto int, err error)
func parsePort(service string) (port int, needsLookup bool)
func partialDeadline(now, deadline time.Time, addrsRemaining int) (time.Time, error)
func randInt() int
func randIntn(n int) int
func readFull(r io.Reader) (all []byte, err error)
func readHosts()
func readProtocols()
func readServices()
func releaseThread()
func removeComment(line []byte) []byte
func reverseaddr(addr string) (arpa string, err error)
func roundDurationUp(d time.Duration, to time.Duration) time.Duration
func selfConnect(fd *netFD, err error) bool
func sendFile(c *netFD, r io.Reader) (written int64, err error, handled bool)
func setDefaultListenerSockopts(s int) error
func setDefaultMulticastSockopts(s int) error
func setDefaultSockopts(s, family, sotype int, ipv6only bool) error
func setIPv4MreqToInterface(mreq *syscall.IPMreq, ifi *Interface) error
func setIPv4MulticastInterface(fd *netFD, ifi *Interface) error
func setIPv4MulticastLoopback(fd *netFD, v bool) error
func setIPv6MulticastInterface(fd *netFD, ifi *Interface) error
func setIPv6MulticastLoopback(fd *netFD, v bool) error
func setKeepAlive(fd *netFD, keepalive bool) error
func setKeepAlivePeriod(fd *netFD, d time.Duration) error
func setLinger(fd *netFD, sec int) error
func setNoDelay(fd *netFD, noDelay bool) error
func setReadBuffer(fd *netFD, bytes int) error
func setWriteBuffer(fd *netFD, bytes int) error
func simpleMaskLength(mask IPMask) int
func skipToAnswer(p *dnsmessage.Parser, qtype dnsmessage.Type) error
func socket(ctx context.Context, net string, family, sotype, proto int, ipv6only bool, laddr, raddr sockaddr, ctrlFn func(string, string, syscall.RawConn) error) (fd *netFD, err error)
func sortByRFC6724(addrs []IPAddr)
func sortByRFC6724withSrcs(addrs []IPAddr, srcs []IP)
func sotypeToNet(sotype int) string
func splice(c *netFD, r io.Reader) (written int64, err error, handled bool)
func splitAtBytes(s string, t string) []string
func splitHostZone(s string) (host, zone string)
func spuriousENOTAVAIL(err error) bool
func stat(name string) (mtime time.Time, size int64, err error)
func stringsEqualFold(s, t string) bool
func stringsHasPrefix(s, prefix string) bool
func stringsHasSuffix(s, suffix string) bool
func stringsHasSuffixFold(s, suffix string) bool
func stripIPv4Header(n int, b []byte) int
func supportsIPv4() bool
func supportsIPv4map() bool
func supportsIPv6() bool
func sysSocket(family, sotype, proto int) (int, error)
func trimSpace(x []byte) []byte
func ubtoa(dst []byte, start int, v byte) int
func uitoa(val uint) string
func unixSocket(ctx context.Context, net string, laddr, raddr sockaddr, mode string, ctrlFn func(string, string, syscall.RawConn) error) (*netFD, error)
func withUnexpiredValuesPreserved(lookupCtx context.Context) context.Context
func wrapSyscallError(name string, err error) error
func xtoi(s string) (n int, i int, ok bool)
func xtoi2(s string, e byte) (byte, bool)
type Addr
    func newAddr(ifam *syscall.IfAddrmsg, attrs []syscall.NetlinkRouteAttr) Addr
    func parseProcNetIGMP(path string, ifi *Interface) []Addr
    func parseProcNetIGMP6(path string, ifi *Interface) []Addr
    func sockaddrToIP(sa syscall.Sockaddr) Addr
    func sockaddrToTCP(sa syscall.Sockaddr) Addr
    func sockaddrToUDP(sa syscall.Sockaddr) Addr
    func sockaddrToUnix(sa syscall.Sockaddr) Addr
    func sockaddrToUnixgram(sa syscall.Sockaddr) Addr
    func sockaddrToUnixpacket(sa syscall.Sockaddr) Addr
type AddrError
    func (e *AddrError) Error() string
    func (e *AddrError) Temporary() bool
    func (e *AddrError) Timeout() bool
type Buffers
    func (v *Buffers) Read(p []byte) (n int, err error)
    func (v *Buffers) WriteTo(w io.Writer) (n int64, err error)
    func (v *Buffers) consume(n int64)
type Conn
type DNSConfigError
    func (e *DNSConfigError) Error() string
    func (e *DNSConfigError) Temporary() bool
    func (e *DNSConfigError) Timeout() bool
    func (e *DNSConfigError) Unwrap() error
type DNSError
    func (e *DNSError) Error() string
    func (e *DNSError) Temporary() bool
    func (e *DNSError) Timeout() bool
type Dialer
    func (d *Dialer) Dial(network, address string) (Conn, error)
    func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error)
    func (d *Dialer) deadline(ctx context.Context, now time.Time) (earliest time.Time)
    func (d *Dialer) dualStack() bool
    func (d *Dialer) fallbackDelay() time.Duration
    func (d *Dialer) resolver() *Resolver
type Error
type Flags
    func linkFlags(rawFlags uint32) Flags
    func (f Flags) String() string
type HardwareAddr
    func (a HardwareAddr) String() string
type IP
    func IPv4(a, b, c, d byte) IP
    func ParseIP(s string) IP
    func copyIP(x IP) IP
    func loopbackIP(net string) IP
    func parseIPZone(s string) (IP, string)
    func parseIPv4(s string) IP
    func parseIPv6(s string) (ip IP)
    func parseIPv6Zone(s string) (IP, string)
    func srcAddrs(addrs []IPAddr) []IP
    func (ip IP) DefaultMask() IPMask
    func (ip IP) Equal(x IP) bool
    func (ip IP) IsGlobalUnicast() bool
    func (ip IP) IsInterfaceLocalMulticast() bool
    func (ip IP) IsLinkLocalMulticast() bool
    func (ip IP) IsLinkLocalUnicast() bool
    func (ip IP) IsLoopback() bool
    func (ip IP) IsMulticast() bool
    func (ip IP) IsUnspecified() bool
    func (ip IP) MarshalText() ([]byte, error)
    func (ip IP) Mask(mask IPMask) IP
    func (ip IP) String() string
    func (ip IP) To16() IP
    func (ip IP) To4() IP
    func (ip *IP) UnmarshalText(text []byte) error
    func (ip IP) matchAddrFamily(x IP) bool
type IPAddr
    func goLookupIPFiles(name string) (addrs []IPAddr)
    func (a *IPAddr) Network() string
    func (a *IPAddr) String() string
    func (a *IPAddr) family() int
    func (a *IPAddr) isWildcard() bool
    func (a *IPAddr) opAddr() Addr
    func (a *IPAddr) sockaddr(family int) (syscall.Sockaddr, error)
    func (a *IPAddr) toLocal(net string) sockaddr
type IPConn
    func newIPConn(fd *netFD) *IPConn
    func (c *IPConn) Close() error
    func (c *IPConn) File() (f *os.File, err error)
    func (c *IPConn) LocalAddr() Addr
    func (c *IPConn) Read(b []byte) (int, error)
    func (c *IPConn) ReadFrom(b []byte) (int, Addr, error)
    func (c *IPConn) ReadFromIP(b []byte) (int, *IPAddr, error)
    func (c *IPConn) ReadMsgIP(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error)
    func (c *IPConn) RemoteAddr() Addr
    func (c *IPConn) SetDeadline(t time.Time) error
    func (c *IPConn) SetReadBuffer(bytes int) error
    func (c *IPConn) SetReadDeadline(t time.Time) error
    func (c *IPConn) SetWriteBuffer(bytes int) error
    func (c *IPConn) SetWriteDeadline(t time.Time) error
    func (c *IPConn) SyscallConn() (syscall.RawConn, error)
    func (c *IPConn) Write(b []byte) (int, error)
    func (c *IPConn) WriteMsgIP(b, oob []byte, addr *IPAddr) (n, oobn int, err error)
    func (c *IPConn) WriteTo(b []byte, addr Addr) (int, error)
    func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (int, error)
    func (c *IPConn) ok() bool
    func (c *IPConn) readFrom(b []byte) (int, *IPAddr, error)
    func (c *IPConn) readMsg(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error)
    func (c *IPConn) writeBuffers(v *Buffers) (int64, error)
    func (c *IPConn) writeMsg(b, oob []byte, addr *IPAddr) (n, oobn int, err error)
    func (c *IPConn) writeTo(b []byte, addr *IPAddr) (int, error)
type IPMask
    func CIDRMask(ones, bits int) IPMask
    func IPv4Mask(a, b, c, d byte) IPMask
    func (m IPMask) Size() (ones, bits int)
    func (m IPMask) String() string
type IPNet
    func mustCIDR(s string) *IPNet
    func (n *IPNet) Contains(ip IP) bool
    func (n *IPNet) Network() string
    func (n *IPNet) String() string
type Interface
    func newLink(ifim *syscall.IfInfomsg, attrs []syscall.NetlinkRouteAttr) *Interface
    func (ifi *Interface) Addrs() ([]Addr, error)
    func (ifi *Interface) MulticastAddrs() ([]Addr, error)
type InvalidAddrError
    func (e InvalidAddrError) Error() string
    func (e InvalidAddrError) Temporary() bool
    func (e InvalidAddrError) Timeout() bool
type ListenConfig
    func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error)
    func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error)
type Listener
type MX
type NS
type OpError
    func (e *OpError) Error() string
    func (e *OpError) Temporary() bool
    func (e *OpError) Timeout() bool
    func (e *OpError) Unwrap() error
type PacketConn
type ParseError
    func (e *ParseError) Error() string
type Resolver
    func (r *Resolver) LookupAddr(ctx context.Context, addr string) ([]string, error)
    func (r *Resolver) LookupCNAME(ctx context.Context, host string) (string, error)
    func (r *Resolver) LookupHost(ctx context.Context, host string) (addrs []string, err error)
    func (r *Resolver) LookupIP(ctx context.Context, network, host string) ([]IP, error)
    func (r *Resolver) LookupIPAddr(ctx context.Context, host string) ([]IPAddr, error)
    func (r *Resolver) LookupMX(ctx context.Context, name string) ([]*MX, error)
    func (r *Resolver) LookupNS(ctx context.Context, name string) ([]*NS, error)
    func (r *Resolver) LookupPort(ctx context.Context, network, service string) (port int, err error)
    func (r *Resolver) LookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error)
    func (r *Resolver) LookupTXT(ctx context.Context, name string) ([]string, error)
    func (r *Resolver) dial(ctx context.Context, network, server string) (Conn, error)
    func (r *Resolver) exchange(ctx context.Context, server string, q dnsmessage.Question, timeout time.Duration, useTCP bool) (dnsmessage.Parser, dnsmessage.Header, error)
    func (r *Resolver) getLookupGroup() *singleflight.Group
    func (r *Resolver) goLookupCNAME(ctx context.Context, host string) (string, error)
    func (r *Resolver) goLookupHost(ctx context.Context, name string) (addrs []string, err error)
    func (r *Resolver) goLookupHostOrder(ctx context.Context, name string, order hostLookupOrder) (addrs []string, err error)
    func (r *Resolver) goLookupIP(ctx context.Context, host string) (addrs []IPAddr, err error)
    func (r *Resolver) goLookupIPCNAMEOrder(ctx context.Context, name string, order hostLookupOrder) (addrs []IPAddr, cname dnsmessage.Name, err error)
    func (r *Resolver) goLookupPTR(ctx context.Context, addr string) ([]string, error)
    func (r *Resolver) internetAddrList(ctx context.Context, net, addr string) (addrList, error)
    func (r *Resolver) lookup(ctx context.Context, name string, qtype dnsmessage.Type) (dnsmessage.Parser, string, error)
    func (r *Resolver) lookupAddr(ctx context.Context, addr string) ([]string, error)
    func (r *Resolver) lookupCNAME(ctx context.Context, name string) (string, error)
    func (r *Resolver) lookupHost(ctx context.Context, host string) (addrs []string, err error)
    func (r *Resolver) lookupIP(ctx context.Context, network, host string) (addrs []IPAddr, err error)
    func (r *Resolver) lookupIPAddr(ctx context.Context, network, host string) ([]IPAddr, error)
    func (r *Resolver) lookupMX(ctx context.Context, name string) ([]*MX, error)
    func (r *Resolver) lookupNS(ctx context.Context, name string) ([]*NS, error)
    func (r *Resolver) lookupPort(ctx context.Context, network, service string) (int, error)
    func (r *Resolver) lookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error)
    func (r *Resolver) lookupTXT(ctx context.Context, name string) ([]string, error)
    func (r *Resolver) preferGo() bool
    func (r *Resolver) resolveAddrList(ctx context.Context, op, network, addr string, hint Addr) (addrList, error)
    func (r *Resolver) strictErrors() bool
    func (r *Resolver) tryOneName(ctx context.Context, cfg *dnsConfig, name string, qtype dnsmessage.Type) (dnsmessage.Parser, string, error)
type SRV
type TCPAddr
    func (a *TCPAddr) Network() string
    func (a *TCPAddr) String() string
    func (a *TCPAddr) family() int
    func (a *TCPAddr) isWildcard() bool
    func (a *TCPAddr) opAddr() Addr
    func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, error)
    func (a *TCPAddr) toLocal(net string) sockaddr
type TCPConn
    func newTCPConn(fd *netFD) *TCPConn
    func (c *TCPConn) Close() error
    func (c *TCPConn) CloseRead() error
    func (c *TCPConn) CloseWrite() error
    func (c *TCPConn) File() (f *os.File, err error)
    func (c *TCPConn) LocalAddr() Addr
    func (c *TCPConn) Read(b []byte) (int, error)
    func (c *TCPConn) ReadFrom(r io.Reader) (int64, error)
    func (c *TCPConn) RemoteAddr() Addr
    func (c *TCPConn) SetDeadline(t time.Time) error
    func (c *TCPConn) SetKeepAlive(keepalive bool) error
    func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error
    func (c *TCPConn) SetLinger(sec int) error
    func (c *TCPConn) SetNoDelay(noDelay bool) error
    func (c *TCPConn) SetReadBuffer(bytes int) error
    func (c *TCPConn) SetReadDeadline(t time.Time) error
    func (c *TCPConn) SetWriteBuffer(bytes int) error
    func (c *TCPConn) SetWriteDeadline(t time.Time) error
    func (c *TCPConn) SyscallConn() (syscall.RawConn, error)
    func (c *TCPConn) Write(b []byte) (int, error)
    func (c *TCPConn) ok() bool
    func (c *TCPConn) readFrom(r io.Reader) (int64, error)
    func (c *TCPConn) writeBuffers(v *Buffers) (int64, error)
type TCPListener
    func (l *TCPListener) Accept() (Conn, error)
    func (l *TCPListener) AcceptTCP() (*TCPConn, error)
    func (l *TCPListener) Addr() Addr
    func (l *TCPListener) Close() error
    func (l *TCPListener) File() (f *os.File, err error)
    func (l *TCPListener) SetDeadline(t time.Time) error
    func (l *TCPListener) SyscallConn() (syscall.RawConn, error)
    func (ln *TCPListener) accept() (*TCPConn, error)
    func (ln *TCPListener) close() error
    func (ln *TCPListener) file() (*os.File, error)
    func (ln *TCPListener) ok() bool
type UDPAddr
    func (a *UDPAddr) Network() string
    func (a *UDPAddr) String() string
    func (a *UDPAddr) family() int
    func (a *UDPAddr) isWildcard() bool
    func (a *UDPAddr) opAddr() Addr
    func (a *UDPAddr) sockaddr(family int) (syscall.Sockaddr, error)
    func (a *UDPAddr) toLocal(net string) sockaddr
type UDPConn
    func newUDPConn(fd *netFD) *UDPConn
    func (c *UDPConn) Close() error
    func (c *UDPConn) File() (f *os.File, err error)
    func (c *UDPConn) LocalAddr() Addr
    func (c *UDPConn) Read(b []byte) (int, error)
    func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error)
    func (c *UDPConn) ReadFromUDP(b []byte) (int, *UDPAddr, error)
    func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)
    func (c *UDPConn) RemoteAddr() Addr
    func (c *UDPConn) SetDeadline(t time.Time) error
    func (c *UDPConn) SetReadBuffer(bytes int) error
    func (c *UDPConn) SetReadDeadline(t time.Time) error
    func (c *UDPConn) SetWriteBuffer(bytes int) error
    func (c *UDPConn) SetWriteDeadline(t time.Time) error
    func (c *UDPConn) SyscallConn() (syscall.RawConn, error)
    func (c *UDPConn) Write(b []byte) (int, error)
    func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error)
    func (c *UDPConn) WriteTo(b []byte, addr Addr) (int, error)
    func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error)
    func (c *UDPConn) ok() bool
    func (c *UDPConn) readFrom(b []byte) (int, *UDPAddr, error)
    func (c *UDPConn) readMsg(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)
    func (c *UDPConn) writeBuffers(v *Buffers) (int64, error)
    func (c *UDPConn) writeMsg(b, oob []byte, addr *UDPAddr) (n, oobn int, err error)
    func (c *UDPConn) writeTo(b []byte, addr *UDPAddr) (int, error)
type UnixAddr
    func (a *UnixAddr) Network() string
    func (a *UnixAddr) String() string
    func (a *UnixAddr) family() int
    func (a *UnixAddr) isWildcard() bool
    func (a *UnixAddr) opAddr() Addr
    func (a *UnixAddr) sockaddr(family int) (syscall.Sockaddr, error)
    func (a *UnixAddr) toLocal(net string) sockaddr
type UnixConn
    func newUnixConn(fd *netFD) *UnixConn
    func (c *UnixConn) Close() error
    func (c *UnixConn) CloseRead() error
    func (c *UnixConn) CloseWrite() error
    func (c *UnixConn) File() (f *os.File, err error)
    func (c *UnixConn) LocalAddr() Addr
    func (c *UnixConn) Read(b []byte) (int, error)
    func (c *UnixConn) ReadFrom(b []byte) (int, Addr, error)
    func (c *UnixConn) ReadFromUnix(b []byte) (int, *UnixAddr, error)
    func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error)
    func (c *UnixConn) RemoteAddr() Addr
    func (c *UnixConn) SetDeadline(t time.Time) error
    func (c *UnixConn) SetReadBuffer(bytes int) error
    func (c *UnixConn) SetReadDeadline(t time.Time) error
    func (c *UnixConn) SetWriteBuffer(bytes int) error
    func (c *UnixConn) SetWriteDeadline(t time.Time) error
    func (c *UnixConn) SyscallConn() (syscall.RawConn, error)
    func (c *UnixConn) Write(b []byte) (int, error)
    func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err error)
    func (c *UnixConn) WriteTo(b []byte, addr Addr) (int, error)
    func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (int, error)
    func (c *UnixConn) ok() bool
    func (c *UnixConn) readFrom(b []byte) (int, *UnixAddr, error)
    func (c *UnixConn) readMsg(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error)
    func (c *UnixConn) writeBuffers(v *Buffers) (int64, error)
    func (c *UnixConn) writeMsg(b, oob []byte, addr *UnixAddr) (n, oobn int, err error)
    func (c *UnixConn) writeTo(b []byte, addr *UnixAddr) (int, error)
type UnixListener
    func (l *UnixListener) Accept() (Conn, error)
    func (l *UnixListener) AcceptUnix() (*UnixConn, error)
    func (l *UnixListener) Addr() Addr
    func (l *UnixListener) Close() error
    func (l *UnixListener) File() (f *os.File, err error)
    func (l *UnixListener) SetDeadline(t time.Time) error
    func (l *UnixListener) SetUnlinkOnClose(unlink bool)
    func (l *UnixListener) SyscallConn() (syscall.RawConn, error)
    func (ln *UnixListener) accept() (*UnixConn, error)
    func (ln *UnixListener) close() error
    func (ln *UnixListener) file() (*os.File, error)
    func (ln *UnixListener) ok() bool
type UnknownNetworkError
    func (e UnknownNetworkError) Error() string
    func (e UnknownNetworkError) Temporary() bool
    func (e UnknownNetworkError) Timeout() bool
type addrList
    func (addrs addrList) first(strategy func(Addr) bool) Addr
    func (addrs addrList) forResolve(network, addr string) Addr
    func (addrs addrList) partition(strategy func(Addr) bool) (primaries, fallbacks addrList)
type addrinfoErrno
    func (eai addrinfoErrno) Error() string
    func (eai addrinfoErrno) Temporary() bool
    func (eai addrinfoErrno) Timeout() bool
type buffersWriter
type byMaskLength
    func (s byMaskLength) Len() int
    func (s byMaskLength) Less(i, j int) bool
    func (s byMaskLength) Swap(i, j int)
type byPref
    func (s byPref) Len() int
    func (s byPref) Less(i, j int) bool
    func (s byPref) Swap(i, j int)
    func (s byPref) sort()
type byPriorityWeight
    func (s byPriorityWeight) Len() int
    func (s byPriorityWeight) Less(i, j int) bool
    func (s byPriorityWeight) Swap(i, j int)
    func (addrs byPriorityWeight) shuffleByWeight()
    func (addrs byPriorityWeight) sort()
type byRFC6724
    func (s *byRFC6724) Len() int
    func (s *byRFC6724) Less(i, j int) bool
    func (s *byRFC6724) Swap(i, j int)
type conf
    func systemConf() *conf
    func (c *conf) canUseCgo() bool
    func (c *conf) hostLookupOrder(r *Resolver, hostname string) (ret hostLookupOrder)
type conn
    func (c *conn) Close() error
    func (c *conn) File() (f *os.File, err error)
    func (c *conn) LocalAddr() Addr
    func (c *conn) Read(b []byte) (int, error)
    func (c *conn) RemoteAddr() Addr
    func (c *conn) SetDeadline(t time.Time) error
    func (c *conn) SetReadBuffer(bytes int) error
    func (c *conn) SetReadDeadline(t time.Time) error
    func (c *conn) SetWriteBuffer(bytes int) error
    func (c *conn) SetWriteDeadline(t time.Time) error
    func (c *conn) Write(b []byte) (int, error)
    func (c *conn) ok() bool
    func (c *conn) writeBuffers(v *Buffers) (int64, error)
type dnsConfig
    func dnsReadConfig(filename string) *dnsConfig
    func (conf *dnsConfig) nameList(name string) []string
    func (c *dnsConfig) serverOffset() uint32
type file
    func (f *file) close()
    func (f *file) getLineFromData() (s string, ok bool)
    func (f *file) readLine() (s string, ok bool)
type fileAddr
    func (fileAddr) Network() string
    func (f fileAddr) String() string
type hostLookupOrder
    func (o hostLookupOrder) String() string
type ipAttr
    func ipAttrOf(ip IP) ipAttr
type ipLookupResult
type ipStackCapabilities
    func (p *ipStackCapabilities) probe()
type ipv6ZoneCache
    func (zc *ipv6ZoneCache) index(name string) int
    func (zc *ipv6ZoneCache) name(index int) string
    func (zc *ipv6ZoneCache) update(ift []Interface, force bool) (updated bool)
type netFD
    func (fd *netFD) Close() error
    func (fd *netFD) Read(p []byte) (n int, err error)
    func (fd *netFD) SetDeadline(t time.Time) error
    func (fd *netFD) SetReadDeadline(t time.Time) error
    func (fd *netFD) SetWriteDeadline(t time.Time) error
    func (fd *netFD) Write(p []byte) (nn int, err error)
    func (fd *netFD) accept() (netfd *netFD, err error)
    func (fd *netFD) addrFunc() func(syscall.Sockaddr) Addr
    func (fd *netFD) closeRead() error
    func (fd *netFD) closeWrite() error
    func (fd *netFD) connect(ctx context.Context, la, ra syscall.Sockaddr) (rsa syscall.Sockaddr, ret error)
    func (fd *netFD) ctrlNetwork() string
    func (fd *netFD) dial(ctx context.Context, laddr, raddr sockaddr, ctrlFn func(string, string, syscall.RawConn) error) error
    func (fd *netFD) dup() (f *os.File, err error)
    func (fd *netFD) init() error
    func (fd *netFD) listenDatagram(laddr sockaddr, ctrlFn func(string, string, syscall.RawConn) error) error
    func (fd *netFD) listenStream(laddr sockaddr, backlog int, ctrlFn func(string, string, syscall.RawConn) error) error
    func (fd *netFD) name() string
    func (fd *netFD) readFrom(p []byte) (n int, sa syscall.Sockaddr, err error)
    func (fd *netFD) readMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.Sockaddr, err error)
    func (fd *netFD) setAddr(laddr, raddr Addr)
    func (fd *netFD) shutdown(how int) error
    func (fd *netFD) writeBuffers(v *Buffers) (n int64, err error)
    func (fd *netFD) writeMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err error)
    func (fd *netFD) writeTo(p []byte, sa syscall.Sockaddr) (n int, err error)
type nssConf
    func parseNSSConf(r io.Reader) *nssConf
    func parseNSSConfFile(file string) *nssConf
type nssCriterion
    func (c nssCriterion) standardStatusAction(last bool) bool
type nssSource
    func (s nssSource) standardCriteria() bool
type onlyValuesCtx
    func (ovc *onlyValuesCtx) Value(key interface{}) interface{}
type pipe
    func (p *pipe) Close() error
    func (*pipe) LocalAddr() Addr
    func (p *pipe) Read(b []byte) (int, error)
    func (*pipe) RemoteAddr() Addr
    func (p *pipe) SetDeadline(t time.Time) error
    func (p *pipe) SetReadDeadline(t time.Time) error
    func (p *pipe) SetWriteDeadline(t time.Time) error
    func (p *pipe) Write(b []byte) (int, error)
    func (p *pipe) read(b []byte) (n int, err error)
    func (p *pipe) write(b []byte) (n int, err error)
type pipeAddr
    func (pipeAddr) Network() string
    func (pipeAddr) String() string
type pipeDeadline
    func makePipeDeadline() pipeDeadline
    func (d *pipeDeadline) set(t time.Time)
    func (d *pipeDeadline) wait() chan struct{}
type policyTable
    func (t policyTable) Classify(ip IP) policyTableEntry
type policyTableEntry
type portLookupResult
type rawConn
    func (c *rawConn) Control(f func(uintptr)) error
    func (c *rawConn) Read(f func(uintptr) bool) error
    func (c *rawConn) Write(f func(uintptr) bool) error
    func (c *rawConn) ok() bool
type rawListener
    func (c *rawListener) Control(f func(uintptr)) error
    func (l *rawListener) Read(func(uintptr) bool) error
    func (l *rawListener) Write(func(uintptr) bool) error
    func (c *rawListener) ok() bool
type resolverConfig
    func (conf *resolverConfig) init()
    func (conf *resolverConfig) releaseSema()
    func (conf *resolverConfig) tryAcquireSema() bool
    func (conf *resolverConfig) tryUpdate(name string)
type reverseLookupResult
type scope
    func classifyScope(ip IP) scope
type sockaddr
type sysDialer
    func (sd *sysDialer) dialIP(ctx context.Context, laddr, raddr *IPAddr) (*IPConn, error)
    func (sd *sysDialer) dialParallel(ctx context.Context, primaries, fallbacks addrList) (Conn, error)
    func (sd *sysDialer) dialSerial(ctx context.Context, ras addrList) (Conn, error)
    func (sd *sysDialer) dialSingle(ctx context.Context, ra Addr) (c Conn, err error)
    func (sd *sysDialer) dialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error)
    func (sd *sysDialer) dialUDP(ctx context.Context, laddr, raddr *UDPAddr) (*UDPConn, error)
    func (sd *sysDialer) dialUnix(ctx context.Context, laddr, raddr *UnixAddr) (*UnixConn, error)
    func (sd *sysDialer) doDialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error)
type sysListener
    func (sl *sysListener) listenIP(ctx context.Context, laddr *IPAddr) (*IPConn, error)
    func (sl *sysListener) listenMulticastUDP(ctx context.Context, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)
    func (sl *sysListener) listenTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error)
    func (sl *sysListener) listenUDP(ctx context.Context, laddr *UDPAddr) (*UDPConn, error)
    func (sl *sysListener) listenUnix(ctx context.Context, laddr *UnixAddr) (*UnixListener, error)
    func (sl *sysListener) listenUnixgram(ctx context.Context, laddr *UnixAddr) (*UnixConn, error)
type temporary
type timeout
type timeoutError
    func (e *timeoutError) Error() string
    func (e *timeoutError) Temporary() bool
    func (e *timeoutError) Timeout() bool
type writerOnly
Bugs

Package files

addrselect.go cgo_linux.go cgo_resnew.go cgo_socknew.go cgo_unix.go conf.go dial.go dnsclient.go dnsclient_unix.go dnsconfig_unix.go error_posix.go error_unix.go fd_posix.go fd_unix.go file.go file_unix.go hook.go hook_unix.go hosts.go interface.go interface_linux.go ip.go iprawsock.go iprawsock_posix.go ipsock.go ipsock_posix.go lookup.go lookup_unix.go mac.go net.go nss.go parse.go pipe.go port.go port_unix.go rawconn.go sendfile_linux.go sock_cloexec.go sock_linux.go sock_posix.go sockaddr_posix.go sockopt_linux.go sockopt_posix.go sockoptip_linux.go sockoptip_posix.go splice_linux.go tcpsock.go tcpsock_posix.go tcpsockopt_posix.go tcpsockopt_unix.go udpsock.go udpsock_posix.go unixsock.go unixsock_posix.go writev_unix.go

Constants

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

const (
    nameinfoLen    = 64
    maxNameinfoLen = 4096
)
const (
    // to be used as a useTCP parameter to exchange
    useTCPOnly  = true
    useUDPOrTCP = false
)
const (
    readSyscallName     = "read"
    readFromSyscallName = "recvfrom"
    readMsgSyscallName  = "recvmsg"
    writeSyscallName    = "write"
    writeToSyscallName  = "sendto"
    writeMsgSyscallName = "sendmsg"
)
const (
    // See linux/if_arp.h.
    // Note that Linux doesn't support IPv4 over IPv6 tunneling.
    sysARPHardwareIPv4IPv4 = 768 // IPv4 over IPv4 tunneling
    sysARPHardwareIPv6IPv6 = 769 // IPv6 over IPv6 tunneling
    sysARPHardwareIPv6IPv4 = 776 // IPv6 over IPv4 tunneling
    sysARPHardwareGREIPv4  = 778 // any over GRE over IPv4 tunneling
    sysARPHardwareGREIPv6  = 823 // any over GRE over IPv6 tunneling
)

IP address lengths (bytes).

const (
    IPv4len = 4
    IPv6len = 16
)

Bigger than we need, not too big to worry about overflow

const big = 0xFFFFFF
const cacheMaxAge = 5 * time.Second

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.

const cgoAddrInfoFlags = C.AI_CANONNAME | C.AI_V4MAPPED | C.AI_ALL

defaultTCPKeepAlive is a default constant value for TCPKeepAlive times See golang.org/issue/31510

const (
    defaultTCPKeepAlive = 15 * time.Second
)
const hexDigit = "0123456789abcdef"

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.

const maxPortBufSize = len("mobility-header") + 10
const maxProtoLength = len("RSVP-E2E-IGNORE") + 10 // with room to grow

Variables

var (
    confOnce sync.Once // guards init of confVal via initConfVal
    confVal  = &conf{goos: runtime.GOOS}
)
var (
    errLameReferral              = errors.New("lame referral")
    errCannotUnmarshalDNSMessage = errors.New("cannot unmarshal DNS message")
    errCannotMarshalDNSMessage   = errors.New("cannot marshal DNS message")
    errServerMisbehaving         = errors.New("server misbehaving")
    errInvalidDNSResponse        = errors.New("invalid DNS response")
    errNoAnswerFromDNSServer     = errors.New("no answer from DNS server")

    // errServerTemporarilyMisbehaving is like errServerMisbehaving, except
    // that when it gets translated to a DNSError, the IsTemporary field
    // gets set to true.
    errServerTemporarilyMisbehaving = errors.New("server misbehaving")
)
var (
    defaultNS   = []string{"127.0.0.1:53", "[::1]:53"}
    getHostname = os.Hostname // variable for testing
)
var (
    // if non-nil, overrides dialTCP.
    testHookDialTCP func(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, error)

    testHookHostsPath = "/etc/hosts"
    testHookLookupIP  = func(
        ctx context.Context,
        fn func(context.Context, string, string) ([]IPAddr, error),
        network string,
        host string,
    ) ([]IPAddr, error) {
        return fn(ctx, network, host)
    }
    testHookSetKeepAlive = func(time.Duration) {}
)
var (
    testHookDialChannel  = func() {} // for golang.org/issue/5349
    testHookCanceledDial = func() {} // for golang.org/issue/16523

    // Placeholders for socket system calls.
    socketFunc        func(int, int, int) (int, error)  = syscall.Socket
    connectFunc       func(int, syscall.Sockaddr) error = syscall.Connect
    listenFunc        func(int, int) error              = syscall.Listen
    getsockoptIntFunc func(int, int, int) (int, error)  = syscall.GetsockoptInt
)
var (
    errInvalidInterface         = errors.New("invalid network interface")
    errInvalidInterfaceIndex    = errors.New("invalid network interface index")
    errInvalidInterfaceName     = errors.New("invalid network interface name")
    errNoSuchInterface          = errors.New("no such network interface")
    errNoSuchMulticastInterface = errors.New("no such multicast network interface")
)

Well-known IPv4 addresses

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

Well-known IPv6 addresses

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

Default route masks for IPv4.

var (
    classAMask = IPv4Mask(0xff, 0, 0, 0)
    classBMask = IPv4Mask(0xff, 0xff, 0, 0)
    classCMask = IPv4Mask(0xff, 0xff, 0xff, 0)
)

netGo and netCgo contain the state of the build tags used to build this binary, and whether cgo is available. conf.go mirrors these into conf for easier testing.

var (
    netGo  bool // set true in cgo_stub.go for build tag "netgo" (or no cgo)
    netCgo bool // set true in conf_netcgo.go for build tag "netcgo"
)

Various errors contained in OpError.

var (
    // For connection setup operations.
    errNoSuitableAddress = errors.New("no suitable address found")

    // For connection setup and write operations.
    errMissingAddress = errors.New("missing address")

    // For both read and write operations.
    errCanceled         = errors.New("operation was canceled")
    ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection")
)
var (
    // aLongTimeAgo is a non-zero time, far in the past, used for
    // immediate cancellation of dials.
    aLongTimeAgo = time.Unix(1, 0)

    // nonDeadline and noCancel are just zero values for
    // readability with functions taking too many parameters.
    noDeadline = time.Time{}
    noCancel   = (chan struct{})(nil)
)
var (
    _ io.WriterTo = (*Buffers)(nil)
    _ io.Reader   = (*Buffers)(nil)
)

DefaultResolver is the resolver used by the package-level Lookup functions and by Dialers without a specified Resolver.

var DefaultResolver = &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).

var ErrClosed = errClosed
var _ context.Context = (*onlyValuesCtx)(nil)

dnsWaitGroup can be used by tests to wait for all DNS goroutines to complete. This avoids races on the test hooks.

var dnsWaitGroup sync.WaitGroup

errClosed exists just so that the docs for ErrClosed don't mention the internal package poll.

var errClosed = poll.ErrNetClosing

Various errors contained in DNSError.

var (
    errNoSuchHost = errors.New("no such host")
)

errTimeout exists to return the historical "i/o timeout" string for context.DeadlineExceeded. See mapErr. It is also used when Dialer.Deadline is exceeded.

TODO(iant): We could consider changing this to os.ErrDeadlineExceeded in the future, but note that that would conflict with the TODO at mapErr that suggests changing it to context.DeadlineExceeded.

var errTimeout error = &timeoutError{}
var flagNames = []string{
    "up",
    "broadcast",
    "loopback",
    "pointtopoint",
    "multicast",
}

hosts contains known host entries.

var hosts struct {
    sync.Mutex

    // Key for the list of literal IP addresses must be a host
    // name. It would be part of DNS labels, a FQDN or an absolute
    // FQDN.
    // For now the key is converted to lower case for convenience.
    byName map[string][]string

    // Key for the list of host names must be a literal IP address
    // including IPv6 address with zone identifier.
    // We don't support old-classful IP address notation.
    byAddr map[string][]string

    expire time.Time
    path   string
    mtime  time.Time
    size   int64
}
var listenerBacklogCache struct {
    sync.Once
    val int
}
var lookupOrderName = map[hostLookupOrder]string{
    hostLookupCgo:      "cgo",
    hostLookupFilesDNS: "files,dns",
    hostLookupDNSFiles: "dns,files",
    hostLookupFiles:    "files",
    hostLookupDNS:      "dns",
}
var onceReadProtocols sync.Once
var onceReadServices sync.Once

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.

var protocols = map[string]int{
    "icmp":      1,
    "igmp":      2,
    "tcp":       6,
    "udp":       17,
    "ipv6-icmp": 58,
}

RFC 6724 section 2.1.

var rfc6724policyTable = policyTable{
    {
        Prefix:     mustCIDR("::1/128"),
        Precedence: 50,
        Label:      0,
    },
    {
        Prefix:     mustCIDR("::/0"),
        Precedence: 40,
        Label:      1,
    },
    {

        Prefix:     mustCIDR("::ffff:0:0/96"),
        Precedence: 35,
        Label:      4,
    },
    {

        Prefix:     mustCIDR("2002::/16"),
        Precedence: 30,
        Label:      2,
    },
    {

        Prefix:     mustCIDR("2001::/32"),
        Precedence: 5,
        Label:      5,
    },
    {
        Prefix:     mustCIDR("fc00::/7"),
        Precedence: 3,
        Label:      13,
    },
    {
        Prefix:     mustCIDR("::/96"),
        Precedence: 1,
        Label:      3,
    },
    {
        Prefix:     mustCIDR("fec0::/10"),
        Precedence: 1,
        Label:      11,
    },
    {
        Prefix:     mustCIDR("3ffe::/16"),
        Precedence: 1,
        Label:      12,
    },
}

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.

var services = map[string]map[string]int{
    "udp": {
        "domain": 53,
    },
    "tcp": {
        "ftp":    21,
        "ftps":   990,
        "gopher": 70,
        "http":   80,
        "https":  443,
        "imap2":  143,
        "imap3":  220,
        "imaps":  993,
        "pop3":   110,
        "pop3s":  995,
        "smtp":   25,
        "ssh":    22,
        "telnet": 23,
    },
}
var threadLimit chan struct{}
var threadOnce sync.Once
var v4InV6Prefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}
var zoneCache = ipv6ZoneCache{
    toIndex: make(map[string]int),
    toName:  make(map[int]string),
}

func Dial

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

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.

func DialIP

func DialIP(network string, laddr, raddr *IPAddr) (*IPConn, error)

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.

func DialTCP

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

DialTCP acts like Dial for TCP networks.

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

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

func DialTimeout

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

DialTimeout acts like Dial but takes a timeout.

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

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

func DialUDP

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

DialUDP acts like Dial for UDP networks.

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

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

func DialUnix

func DialUnix(network string, laddr, raddr *UnixAddr) (*UnixConn, error)

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.

func FileConn

func FileConn(f *os.File) (c Conn, err error)

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.

func FileListener

func FileListener(f *os.File) (ln Listener, err error)

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.

func FilePacketConn

func FilePacketConn(f *os.File) (c PacketConn, err error)

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.

func InterfaceAddrs

func InterfaceAddrs() ([]Addr, error)

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

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

func InterfaceByIndex

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

InterfaceByIndex returns the interface specified by index.

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

func InterfaceByName

func InterfaceByName(name string) (*Interface, error)

InterfaceByName returns the interface specified by name.

func Interfaces

func Interfaces() ([]Interface, error)

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

func JoinHostPort

func JoinHostPort(host, port string) string

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

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

func Listen

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

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.

func ListenIP

func ListenIP(network string, laddr *IPAddr) (*IPConn, error)

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.

func ListenMulticastUDP

func ListenMulticastUDP(network string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)

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.

func ListenPacket

func ListenPacket(network, address string) (PacketConn, error)

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.

func ListenTCP

func ListenTCP(network string, laddr *TCPAddr) (*TCPListener, error)

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.

func ListenUDP

func ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error)

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.

func ListenUnix

func ListenUnix(network string, laddr *UnixAddr) (*UnixListener, error)

ListenUnix acts like Listen for Unix networks.

The network must be "unix" or "unixpacket".

func ListenUnixgram

func ListenUnixgram(network string, laddr *UnixAddr) (*UnixConn, error)

ListenUnixgram acts like ListenPacket for Unix networks.

The network must be "unixgram".

func LookupAddr

func LookupAddr(addr string) (names []string, err 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.

When using the host C library resolver, at most one result will be returned. To bypass the host resolver, use a custom Resolver.

func LookupCNAME

func LookupCNAME(host string) (cname string, err error)

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.

func LookupHost

func LookupHost(host string) (addrs []string, err error)

LookupHost looks up the given host using the local resolver. It returns a slice of that host's addresses.

func LookupIP

func LookupIP(host string) ([]IP, error)

LookupIP looks up host using the local resolver. It returns a slice of that host's IPv4 and IPv6 addresses.

func LookupMX

func LookupMX(name string) ([]*MX, error)

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.

func LookupNS 1.1

func LookupNS(name string) ([]*NS, error)

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.

func LookupPort

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

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

func LookupSRV

func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error)

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.

func LookupTXT

func LookupTXT(name string) ([]string, error)

LookupTXT returns the DNS TXT records for the given domain name.

func ParseCIDR

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

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

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

Example

192.0.2.1
192.0.2.0/24
2001:db8:a0b:12f0::1
2001:db8::/32

func ParseMAC

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

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

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

func Pipe

func Pipe() (Conn, Conn)

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

func ResolveIPAddr

func ResolveIPAddr(network, address string) (*IPAddr, error)

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.

func ResolveTCPAddr

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

ResolveTCPAddr returns an address of TCP end point.

The network must be a TCP network name.

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

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

func ResolveUDPAddr

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

ResolveUDPAddr returns an address of UDP end point.

The network must be a UDP network name.

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

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

func ResolveUnixAddr

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

ResolveUnixAddr returns an address of Unix domain socket end point.

The network must be a Unix network name.

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

func SplitHostPort

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

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

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

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

func absDomainName

func absDomainName(b []byte) string

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.

func acquireThread

func acquireThread()

func addrTable

func addrTable(ift []Interface, ifi *Interface, msgs []syscall.NetlinkMessage) ([]Addr, error)

func allFF

func allFF(b []byte) bool

func appendHex

func appendHex(dst []byte, i uint32) []byte

Convert i to a hexadecimal string. Leading zeros are not printed.

func avoidDNS

func avoidDNS(name string) bool

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.

func boolint

func boolint(b bool) int

Boolean to int.

func cgoIPLookup

func cgoIPLookup(result chan<- ipLookupResult, network, name string)

func cgoLookupAddrPTR

func cgoLookupAddrPTR(addr string, sa *C.struct_sockaddr, salen C.socklen_t) (names []string, err error)

func cgoLookupCNAME

func cgoLookupCNAME(ctx context.Context, name string) (cname string, err error, completed bool)

func cgoLookupHost

func cgoLookupHost(ctx context.Context, name string) (hosts []string, err error, completed bool)

func cgoLookupIP

func cgoLookupIP(ctx context.Context, network, name string) (addrs []IPAddr, err error, completed bool)

func cgoLookupIPCNAME

func cgoLookupIPCNAME(network, name string) (addrs []IPAddr, cname string, err error)

func cgoLookupPTR

func cgoLookupPTR(ctx context.Context, addr string) (names []string, err error, completed bool)

func cgoLookupPort

func cgoLookupPort(ctx context.Context, network, service string) (port int, err error, completed bool)

func cgoLookupServicePort

func cgoLookupServicePort(hints *C.struct_addrinfo, network, service string) (port int, err error)

func cgoNameinfoPTR

func cgoNameinfoPTR(b []byte, sa *C.struct_sockaddr, salen C.socklen_t) (int, error)

func cgoPortLookup

func cgoPortLookup(result chan<- portLookupResult, hints *C.struct_addrinfo, network, service string)

func cgoReverseLookup

func cgoReverseLookup(result chan<- reverseLookupResult, addr string, sa *C.struct_sockaddr, salen C.socklen_t)

func cgoSockaddr

func cgoSockaddr(ip IP, zone string) (*C.struct_sockaddr, C.socklen_t)

func cgoSockaddrInet4

func cgoSockaddrInet4(ip IP) *C.struct_sockaddr

func cgoSockaddrInet6

func cgoSockaddrInet6(ip IP, zone int) *C.struct_sockaddr

func checkHeader

func checkHeader(p *dnsmessage.Parser, h dnsmessage.Header) error

checkHeader performs basic sanity checks on the header.

func checkResponse

func checkResponse(reqID uint16, reqQues dnsmessage.Question, respHdr dnsmessage.Header, respQues dnsmessage.Question) bool

func commonPrefixLen

func commonPrefixLen(a, b IP) (cpl int)

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

func concurrentThreadsLimit

func concurrentThreadsLimit() int

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.

func count

func count(s string, b byte) int

Number of occurrences of b in s.

func countAnyByte

func countAnyByte(s string, t string) int

Count occurrences in s of any bytes in t.

func dnsDefaultSearch

func dnsDefaultSearch() []string

func dnsPacketRoundTrip

func dnsPacketRoundTrip(c Conn, id uint16, query dnsmessage.Question, b []byte) (dnsmessage.Parser, dnsmessage.Header, error)

func dnsStreamRoundTrip

func dnsStreamRoundTrip(c Conn, id uint16, query dnsmessage.Question, b []byte) (dnsmessage.Parser, dnsmessage.Header, error)

func dtoi

func dtoi(s string) (n int, i int, ok bool)

Decimal to integer. Returns number, characters consumed, success.

func dupSocket

func dupSocket(f *os.File) (int, error)

func ensureRooted

func ensureRooted(s string) string

func equalASCIIName

func equalASCIIName(x, y dnsmessage.Name) bool

func fastrand

func fastrand() uint32

provided by runtime

func favoriteAddrFamily

func favoriteAddrFamily(network string, laddr, raddr sockaddr, mode string) (family int, ipv6only bool)

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.

func fileConn

func fileConn(f *os.File) (Conn, error)

func fileListener

func fileListener(f *os.File) (Listener, error)

func filePacketConn

func filePacketConn(f *os.File) (PacketConn, error)

func filterAddrList

func filterAddrList(filter func(IPAddr) bool, ips []IPAddr, inetaddr func(IPAddr) Addr, originalAddr string) (addrList, error)

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.

func foreachField

func foreachField(x []byte, fn func(field []byte) error) error

foreachField runs fn on each non-empty run of non-space bytes in x. It returns the first non-nil error returned by fn.

func foreachLine

func foreachLine(x []byte, fn func(line []byte) error) error

foreachLine runs fn on each line of x. Each line (except for possibly the last) ends in '\n'. It returns the first non-nil error returned by fn.

func genericReadFrom

func genericReadFrom(w io.Writer, r io.Reader) (n int64, err error)

Fallback implementation of io.ReaderFrom's ReadFrom, when sendfile isn't applicable.

func getFields

func getFields(s string) []string

func goDebugNetDNS

func goDebugNetDNS() (dnsMode string, debugLevel int)

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.

func goDebugString

func goDebugString(key string) string

goDebugString returns the value of the named GODEBUG key. GODEBUG is of the form "key=val,key2=val2"

func goLookupPort

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

goLookupPort is the native Go implementation of LookupPort.

func hasPrefix

func hasPrefix(s, prefix string) bool

func hexString

func hexString(b []byte) string

func init

func init()

func initConfVal

func initConfVal()

func interfaceAddrTable

func interfaceAddrTable(ifi *Interface) ([]Addr, error)

If the ifi is nil, interfaceAddrTable returns addresses for all network interfaces. Otherwise it returns addresses for a specific interface.

func interfaceByIndex

func interfaceByIndex(ift []Interface, index int) (*Interface, error)

func interfaceMulticastAddrTable

func interfaceMulticastAddrTable(ifi *Interface) ([]Addr, error)

interfaceMulticastAddrTable returns addresses for a specific interface.

func interfaceTable

func interfaceTable(ifindex int) ([]Interface, error)

If the ifindex is zero, interfaceTable returns mappings of all network interfaces. Otherwise it returns a mapping of a specific interface.

func interfaceToIPv4Addr

func interfaceToIPv4Addr(ifi *Interface) (IP, error)

func internetSocket

func internetSocket(ctx context.Context, net string, laddr, raddr sockaddr, sotype, proto int, mode string, ctrlFn func(string, string, syscall.RawConn) error) (fd *netFD, err error)

func ipAddrsEface

func ipAddrsEface(addrs []IPAddr) []interface{}

ipAddrsEface returns an empty interface slice of addrs.

func ipEmptyString

func ipEmptyString(ip IP) string

ipEmptyString is like ip.String except that it returns an empty string when ip is unset.

func ipToSockaddr

func ipToSockaddr(family int, ip IP, port int, zone string) (syscall.Sockaddr, error)

func ipVersion

func ipVersion(network string) byte

ipVersion returns the provided network's IP version: '4', '6' or 0 if network does not end in a '4' or '6' byte.

func ipv4AddrToInterface

func ipv4AddrToInterface(ip IP) (*Interface, error)

func ipv4only

func ipv4only(addr IPAddr) bool

ipv4only reports whether addr is an IPv4 address.

func ipv6only

func ipv6only(addr IPAddr) bool

ipv6only reports whether addr is an IPv6 address except IPv4-mapped IPv6 address.

func isClosedChan

func isClosedChan(c <-chan struct{}) bool

func isConnError

func isConnError(err error) bool

func isDomainName

func isDomainName(s string) bool

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).

func isGateway

func isGateway(h string) bool

isGateway reports whether h should be considered a "gateway" name for the myhostname NSS module.

func isIPv4

func isIPv4(addr Addr) bool

isIPv4 reports whether addr contains an IPv4 address.

func isLocalhost

func isLocalhost(h string) bool

isLocalhost reports whether h should be considered a "localhost" name for the myhostname NSS module.

func isNotIPv4

func isNotIPv4(addr Addr) bool

isNotIPv4 reports whether addr does not contain an IPv4 address.

func isSpace

func isSpace(b byte) bool

isSpace reports whether b is an ASCII space character.

func isZeros

func isZeros(p IP) bool

Is p all zeros?

func itoa

func itoa(val int) string

Convert integer to decimal string.

func joinIPv4Group

func joinIPv4Group(fd *netFD, ifi *Interface, ip IP) error

func joinIPv6Group

func joinIPv6Group(fd *netFD, ifi *Interface, ip IP) error

func kernelVersion

func kernelVersion() (major int, minor int)

func last

func last(s string, b byte) int

Index of rightmost occurrence of b in s.

func listenIPv4MulticastUDP

func listenIPv4MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error

func listenIPv6MulticastUDP

func listenIPv6MulticastUDP(c *UDPConn, ifi *Interface, ip IP) error

func listenerBacklog

func listenerBacklog() int

listenerBacklog is a caching wrapper around maxListenerBacklog.

func lookupIPReturn

func lookupIPReturn(addrsi interface{}, err error, shared bool) ([]IPAddr, error)

lookupIPReturn turns the return values from singleflight.Do into the return values from LookupIP.

func lookupPortMap

func lookupPortMap(network, service string) (port int, error error)

func lookupProtocol

func lookupProtocol(_ context.Context, name string) (int, error)

lookupProtocol looks up IP protocol name in /etc/protocols and returns correspondent protocol number.

func lookupProtocolMap

func lookupProtocolMap(name string) (int, error)

func lookupStaticAddr

func lookupStaticAddr(addr string) []string

lookupStaticAddr looks up the hosts for the given address from /etc/hosts.

func lookupStaticHost

func lookupStaticHost(host string) []string

lookupStaticHost looks up the addresses for the given host from /etc/hosts.

func lowerASCII

func lowerASCII(b byte) byte

lowerASCII returns the ASCII lowercase version of b.

func lowerASCIIBytes

func lowerASCIIBytes(x []byte)

lowerASCIIBytes makes x ASCII lowercase in-place.

func mapErr

func mapErr(err error) error

mapErr maps from the context errors to the historical internal net error values.

TODO(bradfitz): get rid of this after adjusting tests and making context.DeadlineExceeded implement net.Error?

func maxAckBacklog

func maxAckBacklog(n int) int

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.

func maxListenerBacklog

func maxListenerBacklog() int

func minNonzeroTime

func minNonzeroTime(a, b time.Time) time.Time

func networkNumberAndMask

func networkNumberAndMask(n *IPNet) (ip IP, m IPMask)

func newFD

func newFD(sysfd, family, sotype int, net string) (*netFD, error)

func newFileFD

func newFileFD(f *os.File) (*netFD, error)

func newRawConn

func newRawConn(fd *netFD) (*rawConn, error)

func newRawListener

func newRawListener(fd *netFD) (*rawListener, error)

func newRequest

func newRequest(q dnsmessage.Question) (id uint16, udpReq, tcpReq []byte, err error)

func open

func open(name string) (*file, error)

func parseCriteria

func parseCriteria(x []byte) (c []nssCriterion, err error)

parses "foo=bar !foo=bar"

func parseLiteralIP

func parseLiteralIP(addr string) string

func parseNetwork

func parseNetwork(ctx context.Context, network string, needsProto bool) (afnet string, proto int, err error)

func parsePort

func parsePort(service string) (port int, needsLookup bool)

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.

func partialDeadline

func partialDeadline(now, deadline time.Time, addrsRemaining int) (time.Time, error)

partialDeadline returns the deadline to use for a single address, when multiple addresses are pending.

func randInt

func randInt() int

func randIntn

func randIntn(n int) int

func readFull

func readFull(r io.Reader) (all []byte, err error)

func readHosts

func readHosts()

func readProtocols

func readProtocols()

readProtocols loads contents of /etc/protocols into protocols map for quick access.

func readServices

func readServices()

func releaseThread

func releaseThread()

func removeComment

func removeComment(line []byte) []byte

removeComment returns line, removing any '#' byte and any following bytes.

func reverseaddr

func reverseaddr(addr string) (arpa string, err error)

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.

func roundDurationUp

func roundDurationUp(d time.Duration, to time.Duration) time.Duration

roundDurationUp rounds d to the next multiple of to.

func selfConnect

func selfConnect(fd *netFD, err error) bool

func sendFile

func sendFile(c *netFD, r io.Reader) (written int64, err error, handled bool)

sendFile copies the contents of r to c using the sendfile system call to minimize copies.

if handled == true, sendFile returns the number of bytes copied and any non-EOF error.

if handled == false, sendFile performed no work.

func setDefaultListenerSockopts

func setDefaultListenerSockopts(s int) error

func setDefaultMulticastSockopts

func setDefaultMulticastSockopts(s int) error

func setDefaultSockopts

func setDefaultSockopts(s, family, sotype int, ipv6only bool) error

func setIPv4MreqToInterface

func setIPv4MreqToInterface(mreq *syscall.IPMreq, ifi *Interface) error

func setIPv4MulticastInterface

func setIPv4MulticastInterface(fd *netFD, ifi *Interface) error

func setIPv4MulticastLoopback

func setIPv4MulticastLoopback(fd *netFD, v bool) error

func setIPv6MulticastInterface

func setIPv6MulticastInterface(fd *netFD, ifi *Interface) error

func setIPv6MulticastLoopback

func setIPv6MulticastLoopback(fd *netFD, v bool) error

func setKeepAlive

func setKeepAlive(fd *netFD, keepalive bool) error

func setKeepAlivePeriod

func setKeepAlivePeriod(fd *netFD, d time.Duration) error

func setLinger

func setLinger(fd *netFD, sec int) error

func setNoDelay

func setNoDelay(fd *netFD, noDelay bool) error

func setReadBuffer

func setReadBuffer(fd *netFD, bytes int) error

func setWriteBuffer

func setWriteBuffer(fd *netFD, bytes int) error

func simpleMaskLength

func simpleMaskLength(mask IPMask) int

If mask is a sequence of 1 bits followed by 0 bits, return the number of 1 bits.

func skipToAnswer

func skipToAnswer(p *dnsmessage.Parser, qtype dnsmessage.Type) error

func socket

func socket(ctx context.Context, net string, family, sotype, proto int, ipv6only bool, laddr, raddr sockaddr, ctrlFn func(string, string, syscall.RawConn) error) (fd *netFD, err error)

socket returns a network file descriptor that is ready for asynchronous I/O using the network poller.

func sortByRFC6724

func sortByRFC6724(addrs []IPAddr)

func sortByRFC6724withSrcs

func sortByRFC6724withSrcs(addrs []IPAddr, srcs []IP)

func sotypeToNet

func sotypeToNet(sotype int) string

func splice

func splice(c *netFD, r io.Reader) (written int64, err error, handled bool)

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.

func splitAtBytes

func splitAtBytes(s string, t string) []string

Split s at any bytes in t.

func splitHostZone

func splitHostZone(s string) (host, zone string)

func spuriousENOTAVAIL

func spuriousENOTAVAIL(err error) bool

func stat

func stat(name string) (mtime time.Time, size int64, err error)

func stringsEqualFold

func stringsEqualFold(s, t string) bool

stringsEqualFold is strings.EqualFold, ASCII only. It reports whether s and t are equal, ASCII-case-insensitively.

func stringsHasPrefix

func stringsHasPrefix(s, prefix string) bool

stringsHasPrefix is strings.HasPrefix. It reports whether s begins with prefix.

func stringsHasSuffix

func stringsHasSuffix(s, suffix string) bool

stringsHasSuffix is strings.HasSuffix. It reports whether s ends in suffix.

func stringsHasSuffixFold

func stringsHasSuffixFold(s, suffix string) bool

stringsHasSuffixFold reports whether s ends in suffix, ASCII-case-insensitively.

func stripIPv4Header

func stripIPv4Header(n int, b []byte) int

func supportsIPv4

func supportsIPv4() bool

supportsIPv4 reports whether the platform supports IPv4 networking functionality.

func supportsIPv4map

func supportsIPv4map() bool

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.

func supportsIPv6

func supportsIPv6() bool

supportsIPv6 reports whether the platform supports IPv6 networking functionality.

func sysSocket

func sysSocket(family, sotype, proto int) (int, error)

Wrapper around the socket system call that marks the returned file descriptor as nonblocking and close-on-exec.

func trimSpace

func trimSpace(x []byte) []byte

trimSpace returns x without any leading or trailing ASCII whitespace.

func ubtoa

func ubtoa(dst []byte, start int, v byte) int

ubtoa encodes the string form of the integer v to dst[start:] and returns the number of bytes written to dst. The caller must ensure that dst has sufficient length.

func uitoa

func uitoa(val uint) string

Convert unsigned integer to decimal string.

func unixSocket

func unixSocket(ctx context.Context, net string, laddr, raddr sockaddr, mode string, ctrlFn func(string, string, syscall.RawConn) error) (*netFD, error)

func withUnexpiredValuesPreserved

func withUnexpiredValuesPreserved(lookupCtx context.Context) context.Context

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.

func wrapSyscallError

func wrapSyscallError(name string, err error) error

wrapSyscallError takes an error and a syscall name. If the error is a syscall.Errno, it wraps it in a os.SyscallError using the syscall name.

func xtoi

func xtoi(s string) (n int, i int, ok bool)

Hexadecimal to integer. Returns number, characters consumed, success.

func xtoi2

func xtoi2(s string, e byte) (byte, bool)

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.

type Addr

Addr represents a network end point address.

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

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

func newAddr

func newAddr(ifam *syscall.IfAddrmsg, attrs []syscall.NetlinkRouteAttr) Addr

func parseProcNetIGMP

func parseProcNetIGMP(path string, ifi *Interface) []Addr

func parseProcNetIGMP6

func parseProcNetIGMP6(path string, ifi *Interface) []Addr

func sockaddrToIP

func sockaddrToIP(sa syscall.Sockaddr) Addr

func sockaddrToTCP

func sockaddrToTCP(sa syscall.Sockaddr) Addr

func sockaddrToUDP

func sockaddrToUDP(sa syscall.Sockaddr) Addr

func sockaddrToUnix

func sockaddrToUnix(sa syscall.Sockaddr) Addr

func sockaddrToUnixgram

func sockaddrToUnixgram(sa syscall.Sockaddr) Addr

func sockaddrToUnixpacket

func sockaddrToUnixpacket(sa syscall.Sockaddr) Addr

type AddrError

type AddrError struct {
    Err  string
    Addr string
}

func (*AddrError) Error

func (e *AddrError) Error() string

func (*AddrError) Temporary

func (e *AddrError) Temporary() bool

func (*AddrError) Timeout

func (e *AddrError) Timeout() bool

type Buffers 1.8

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").

type Buffers [][]byte

func (*Buffers) Read 1.8

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

func (*Buffers) WriteTo 1.8

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

func (*Buffers) consume

func (v *Buffers) consume(n int64)

type Conn

Conn is a generic stream-oriented network connection.

Multiple goroutines may invoke methods on a Conn simultaneously.

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

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

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

    // LocalAddr returns the local network address.
    LocalAddr() Addr

    // RemoteAddr returns the remote network address.
    RemoteAddr() Addr

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

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

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

type DNSConfigError

DNSConfigError represents an error reading the machine's DNS configuration. (No longer used; kept for compatibility.)

type DNSConfigError struct {
    Err error
}

func (*DNSConfigError) Error

func (e *DNSConfigError) Error() string

func (*DNSConfigError) Temporary

func (e *DNSConfigError) Temporary() bool

func (*DNSConfigError) Timeout

func (e *DNSConfigError) Timeout() bool

func (*DNSConfigError) Unwrap 1.13

func (e *DNSConfigError) Unwrap() error

type DNSError

DNSError represents a DNS lookup error.

type DNSError struct {
    Err         string // description of the error
    Name        string // name looked for
    Server      string // server used
    IsTimeout   bool   // if true, timed out; not all timeouts set this
    IsTemporary bool   // if true, error is temporary; not all errors set this; added in Go 1.6
    IsNotFound  bool   // if true, host could not be found; added in Go 1.13
}

func (*DNSError) Error

func (e *DNSError) Error() string

func (*DNSError) Temporary

func (e *DNSError) Temporary() bool

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.

func (*DNSError) Timeout

func (e *DNSError) Timeout() bool

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.

type Dialer 1.1

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.

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

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

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

    // 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.
    DualStack bool // Go 1.2

    // 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.
    FallbackDelay time.Duration // Go 1.5

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

    // Resolver optionally specifies an alternate resolver to use.
    Resolver *Resolver // Go 1.8

    // 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.
    Cancel <-chan struct{} // Go 1.6

    // If Control is not nil, it is called after creating the network
    // connection but before actually dialing.
    //
    // Network and address parameters passed to Control method 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 func(network, address string, c syscall.RawConn) error // Go 1.11
}

Example

Example (Unix)

func (*Dialer) Dial 1.1

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

Dial connects to the address on the named network.

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

func (*Dialer) DialContext 1.7

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

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

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

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

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

func (*Dialer) deadline

func (d *Dialer) deadline(ctx context.Context, now time.Time) (earliest time.Time)

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.

func (*Dialer) dualStack

func (d *Dialer) dualStack() bool

func (*Dialer) fallbackDelay

func (d *Dialer) fallbackDelay() time.Duration

func (*Dialer) resolver

func (d *Dialer) resolver() *Resolver

type Error

An Error represents a network error.

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

type Flags

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

func linkFlags

func linkFlags(rawFlags uint32) Flags

func (Flags) String

func (f Flags) String() string

type HardwareAddr

A HardwareAddr represents a physical hardware address.

type HardwareAddr []byte

func (HardwareAddr) String

func (a HardwareAddr) String() string

type IP

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.

type IP []byte

func IPv4

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

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

Example

8.8.8.8

func ParseIP

func ParseIP(s string) IP

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

Example

192.0.2.1
2001:db8::68
<nil>

func copyIP

func copyIP(x IP) IP

func loopbackIP

func loopbackIP(net string) IP

func parseIPZone

func parseIPZone(s string) (IP, string)

parseIPZone parses s as an IP address, return it and its associated zone identifier (IPv6 only).

func parseIPv4

func parseIPv4(s string) IP

Parse IPv4 address (d.d.d.d).

func parseIPv6

func parseIPv6(s string) (ip IP)

parseIPv6 parses s as a literal IPv6 address described in RFC 4291 and RFC 5952.

func parseIPv6Zone

func parseIPv6Zone(s string) (IP, string)

parseIPv6Zone parses s as a literal IPv6 address and its associated zone identifier which is described in RFC 4007.

func srcAddrs

func srcAddrs(addrs []IPAddr) []IP

srcsAddrs tries to UDP-connect to each address to see if it has a route. (This doesn't send any packets). The destination port number is irrelevant.

func (IP) DefaultMask

func (ip IP) DefaultMask() IPMask

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

Example

ffffff00

func (IP) Equal

func (ip IP) Equal(x IP) bool

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

func (IP) IsGlobalUnicast

func (ip IP) IsGlobalUnicast() bool

IsGlobalUnicast reports whether ip is a global unicast address.

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

func (IP) IsInterfaceLocalMulticast

func (ip IP) IsInterfaceLocalMulticast() bool

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

func (IP) IsLinkLocalMulticast

func (ip IP) IsLinkLocalMulticast() bool

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

func (IP) IsLinkLocalUnicast

func (ip IP) IsLinkLocalUnicast() bool

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

func (IP) IsLoopback

func (ip IP) IsLoopback() bool

IsLoopback reports whether ip is a loopback address.

func (IP) IsMulticast

func (ip IP) IsMulticast() bool

IsMulticast reports whether ip is a multicast address.

func (IP) IsUnspecified

func (ip IP) IsUnspecified() bool

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

func (IP) MarshalText 1.2

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

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

func (IP) Mask

func (ip IP) Mask(mask IPMask) IP

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

Example

192.0.2.0
2001:db8::

func (IP) String

func (ip IP) String() string

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

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

func (IP) To16

func (ip IP) To16() IP

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

func (IP) To4

func (ip IP) To4() IP

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

func (*IP) UnmarshalText 1.2

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

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

func (IP) matchAddrFamily

func (ip IP) matchAddrFamily(x IP) bool

type IPAddr

IPAddr represents the address of an IP end point.

type IPAddr struct {
    IP   IP
    Zone string // IPv6 scoped addressing zone; added in Go 1.1
}

func goLookupIPFiles

func goLookupIPFiles(name string) (addrs []IPAddr)

lookup entries from /etc/hosts

func (*IPAddr) Network

func (a *IPAddr) Network() string

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

func (*IPAddr) String

func (a *IPAddr) String() string

func (*IPAddr) family

func (a *IPAddr) family() int

func (*IPAddr) isWildcard

func (a *IPAddr) isWildcard() bool

func (*IPAddr) opAddr

func (a *IPAddr) opAddr() Addr

func (*IPAddr) sockaddr

func (a *IPAddr) sockaddr(family int) (syscall.Sockaddr, error)

func (*IPAddr) toLocal

func (a *IPAddr) toLocal(net string) sockaddr

type IPConn

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

type IPConn struct {
    conn
}

func newIPConn

func newIPConn(fd *netFD) *IPConn

func (*IPConn) Close

func (c *IPConn) Close() error

Close closes the connection.

func (*IPConn) File

func (c *IPConn) File() (f *os.File, err error)

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.

func (*IPConn) LocalAddr

func (c *IPConn) LocalAddr() Addr

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

func (*IPConn) Read

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

Read implements the Conn Read method.

func (*IPConn) ReadFrom

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

ReadFrom implements the PacketConn ReadFrom method.

func (*IPConn) ReadFromIP

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

ReadFromIP acts like ReadFrom but returns an IPAddr.

func (*IPConn) ReadMsgIP 1.1

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

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

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

func (*IPConn) RemoteAddr

func (c *IPConn) RemoteAddr() Addr

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

func (*IPConn) SetDeadline

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

SetDeadline implements the Conn SetDeadline method.

func (*IPConn) SetReadBuffer

func (c *IPConn) SetReadBuffer(bytes int) error

SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

func (*IPConn) SetReadDeadline

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

SetReadDeadline implements the Conn SetReadDeadline method.

func (*IPConn) SetWriteBuffer

func (c *IPConn) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

func (*IPConn) SetWriteDeadline

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

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*IPConn) SyscallConn 1.9

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

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

func (*IPConn) Write

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

Write implements the Conn Write method.

func (*IPConn) WriteMsgIP 1.1

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

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.

func (*IPConn) WriteTo

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

WriteTo implements the PacketConn WriteTo method.

func (*IPConn) WriteToIP

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

WriteToIP acts like WriteTo but takes an IPAddr.

func (*IPConn) ok

func (c *IPConn) ok() bool

func (*IPConn) readFrom

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

func (*IPConn) readMsg

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

func (*IPConn) writeBuffers

func (c *IPConn) writeBuffers(v *Buffers) (int64, error)

func (*IPConn) writeMsg

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

func (*IPConn) writeTo

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

type IPMask

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.

type IPMask []byte

func CIDRMask

func CIDRMask(ones, bits int) IPMask

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

Example

fffffffe
ffffffffffffffff0000000000000000

func IPv4Mask

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

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

Example

ffffff00

func (IPMask) Size

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

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

func (IPMask) String

func (m IPMask) String() string

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

type IPNet

An IPNet represents an IP network.

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

func mustCIDR

func mustCIDR(s string) *IPNet

mustCIDR calls ParseCIDR and panics on any error, or if the network is not IPv6.

func (*IPNet) Contains

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

Contains reports whether the network includes ip.

func (*IPNet) Network

func (n *IPNet) Network() string

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

func (*IPNet) String

func (n *IPNet) String() string

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

type Interface

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

type Interface struct {
    Index        int          // positive integer that starts at one, zero is never used
    MTU          int          // maximum transmission unit
    Name         string       // e.g., "en0", "lo0", "eth0.100"
    HardwareAddr HardwareAddr // IEEE MAC-48, EUI-48 and EUI-64 form
    Flags        Flags        // e.g., FlagUp, FlagLoopback, FlagMulticast
}
func newLink(ifim *syscall.IfInfomsg, attrs []syscall.NetlinkRouteAttr) *Interface

func (*Interface) Addrs

func (ifi *Interface) Addrs() ([]Addr, error)

Addrs returns a list of unicast interface addresses for a specific interface.

func (*Interface) MulticastAddrs

func (ifi *Interface) MulticastAddrs() ([]Addr, error)

MulticastAddrs returns a list of multicast, joined group addresses for a specific interface.

type InvalidAddrError

type InvalidAddrError string

func (InvalidAddrError) Error

func (e InvalidAddrError) Error() string

func (InvalidAddrError) Temporary

func (e InvalidAddrError) Temporary() bool

func (InvalidAddrError) Timeout

func (e InvalidAddrError) Timeout() bool

type ListenConfig 1.11

ListenConfig contains options for listening to an address.

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

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

func (*ListenConfig) Listen 1.11

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

Listen announces on the local network address.

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

func (*ListenConfig) ListenPacket 1.11

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

ListenPacket announces on the local network address.

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

type Listener

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

Multiple goroutines may invoke methods on a Listener simultaneously.

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

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

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

Example

type MX

An MX represents a single DNS MX record.

type MX struct {
    Host string
    Pref uint16
}

type NS 1.1

An NS represents a single DNS NS record.

type NS struct {
    Host string
}

type OpError

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

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

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

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

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

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

func (*OpError) Error

func (e *OpError) Error() string

func (*OpError) Temporary

func (e *OpError) Temporary() bool

func (*OpError) Timeout

func (e *OpError) Timeout() bool

func (*OpError) Unwrap 1.13

func (e *OpError) Unwrap() error

type PacketConn

PacketConn is a generic packet-oriented network connection.

Multiple goroutines may invoke methods on a PacketConn simultaneously.

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

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

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

    // LocalAddr returns the local network address.
    LocalAddr() Addr

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

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

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

type ParseError

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

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

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

func (*ParseError) Error

func (e *ParseError) Error() string

type Resolver 1.8

A Resolver looks up names and numbers.

A nil *Resolver is equivalent to a zero Resolver.

type Resolver struct {
    // 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.
    PreferGo bool

    // 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.
    StrictErrors bool // Go 1.9

    // 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.
    Dial func(ctx context.Context, network, address string) (Conn, error) // Go 1.9

    // 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).
    lookupGroup singleflight.Group
}

func (*Resolver) LookupAddr 1.8

func (r *Resolver) LookupAddr(ctx context.Context, addr string) ([]string, 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.

func (*Resolver) LookupCNAME 1.8

func (r *Resolver) LookupCNAME(ctx context.Context, host string) (string, error)

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.

func (*Resolver) LookupHost 1.8

func (r *Resolver) LookupHost(ctx context.Context, host string) (addrs []string, err error)

LookupHost looks up the given host using the local resolver. It returns a slice of that host's addresses.

func (*Resolver) LookupIP 1.15

func (r *Resolver) LookupIP(ctx context.Context, network, host string) ([]IP, error)

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".

func (*Resolver) LookupIPAddr 1.8

func (r *Resolver) LookupIPAddr(ctx context.Context, host string) ([]IPAddr, error)

LookupIPAddr looks up host using the local resolver. It returns a slice of that host's IPv4 and IPv6 addresses.

func (*Resolver) LookupMX 1.8

func (r *Resolver) LookupMX(ctx context.Context, name string) ([]*MX, error)

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.

func (*Resolver) LookupNS 1.8

func (r *Resolver) LookupNS(ctx context.Context, name string) ([]*NS, error)

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.

func (*Resolver) LookupPort 1.8

func (r *Resolver) LookupPort(ctx context.Context, network, service string) (port int, err error)

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

func (*Resolver) LookupSRV 1.8

func (r *Resolver) LookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error)

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.

func (*Resolver) LookupTXT 1.8

func (r *Resolver) LookupTXT(ctx context.Context, name string) ([]string, error)

LookupTXT returns the DNS TXT records for the given domain name.

func (*Resolver) dial

func (r *Resolver) dial(ctx context.Context, network, server string) (Conn, error)

func (*Resolver) exchange

func (r *Resolver) exchange(ctx context.Context, server string, q dnsmessage.Question, timeout time.Duration, useTCP bool) (dnsmessage.Parser, dnsmessage.Header, error)

exchange sends a query on the connection and hopes for a response.

func (*Resolver) getLookupGroup

func (r *Resolver) getLookupGroup() *singleflight.Group

func (*Resolver) goLookupCNAME

func (r *Resolver) goLookupCNAME(ctx context.Context, host string) (string, error)

goLookupCNAME is the native Go (non-cgo) implementation of LookupCNAME.

func (*Resolver) goLookupHost

func (r *Resolver) goLookupHost(ctx context.Context, name string) (addrs []string, err error)

goLookupHost is the native Go implementation of LookupHost. Used only if cgoLookupHost refuses to handle the request (that is, only if cgoLookupHost is the stub in cgo_stub.go). Normally we let cgo use the C library resolver instead of depending on our lookup code, so that Go and C get the same answers.

func (*Resolver) goLookupHostOrder

func (r *Resolver) goLookupHostOrder(ctx context.Context, name string, order hostLookupOrder) (addrs []string, err error)

func (*Resolver) goLookupIP

func (r *Resolver) goLookupIP(ctx context.Context, host string) (addrs []IPAddr, err error)

goLookupIP is the native Go implementation of LookupIP. The libc versions are in cgo_*.go.

func (*Resolver) goLookupIPCNAMEOrder

func (r *Resolver) goLookupIPCNAMEOrder(ctx context.Context, name string, order hostLookupOrder) (addrs []IPAddr, cname dnsmessage.Name, err error)

func (*Resolver) goLookupPTR

func (r *Resolver) goLookupPTR(ctx context.Context, addr string) ([]string, error)

goLookupPTR is the native Go implementation of LookupAddr. Used only if cgoLookupPTR refuses to handle the request (that is, only if cgoLookupPTR is the stub in cgo_stub.go). Normally we let cgo use the C library resolver instead of depending on our lookup code, so that Go and C get the same answers.

func (*Resolver) internetAddrList

func (r *Resolver) internetAddrList(ctx context.Context, net, addr string) (addrList, error)

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.

func (*Resolver) lookup

func (r *Resolver) lookup(ctx context.Context, name string, qtype dnsmessage.Type) (dnsmessage.Parser, string, error)

func (*Resolver) lookupAddr

func (r *Resolver) lookupAddr(ctx context.Context, addr string) ([]string, error)

func (*Resolver) lookupCNAME

func (r *Resolver) lookupCNAME(ctx context.Context, name string) (string, error)

func (*Resolver) lookupHost

func (r *Resolver) lookupHost(ctx context.Context, host string) (addrs []string, err error)

func (*Resolver) lookupIP

func (r *Resolver) lookupIP(ctx context.Context, network, host string) (addrs []IPAddr, err error)

func (*Resolver) lookupIPAddr

func (r *Resolver) lookupIPAddr(ctx context.Context, network, host string) ([]IPAddr, error)

lookupIPAddr looks up host using the local resolver and particular network. It returns a slice of that host's IPv4 and IPv6 addresses.

func (*Resolver) lookupMX

func (r *Resolver) lookupMX(ctx context.Context, name string) ([]*MX, error)

func (*Resolver) lookupNS

func (r *Resolver) lookupNS(ctx context.Context, name string) ([]*NS, error)

func (*Resolver) lookupPort

func (r *Resolver) lookupPort(ctx context.Context, network, service string) (int, error)

func (*Resolver) lookupSRV

func (r *Resolver) lookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error)

func (*Resolver) lookupTXT

func (r *Resolver) lookupTXT(ctx context.Context, name string) ([]string, error)

func (*Resolver) preferGo

func (r *Resolver) preferGo() bool

func (*Resolver) resolveAddrList

func (r *Resolver) resolveAddrList(ctx context.Context, op, network, addr string, hint Addr) (addrList, error)

resolveAddrList resolves addr using hint and returns a list of addresses. The result contains at least one address when error is nil.

func (*Resolver) strictErrors

func (r *Resolver) strictErrors() bool

func (*Resolver) tryOneName

func (r *Resolver) tryOneName(ctx context.Context, cfg *dnsConfig, name string, qtype dnsmessage.Type) (dnsmessage.Parser, string, error)

Do a lookup for a single name, which must be rooted (otherwise answer will not find the answers).

type SRV

An SRV represents a single DNS SRV record.

type SRV struct {
    Target   string
    Port     uint16
    Priority uint16
    Weight   uint16
}

type TCPAddr

TCPAddr represents the address of a TCP end point.

type TCPAddr struct {
    IP   IP
    Port int
    Zone string // IPv6 scoped addressing zone; added in Go 1.1
}

func (*TCPAddr) Network

func (a *TCPAddr) Network() string

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

func (*TCPAddr) String

func (a *TCPAddr) String() string

func (*TCPAddr) family

func (a *TCPAddr) family() int

func (*TCPAddr) isWildcard

func (a *TCPAddr) isWildcard() bool

func (*TCPAddr) opAddr

func (a *TCPAddr) opAddr() Addr

func (*TCPAddr) sockaddr

func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, error)

func (*TCPAddr) toLocal

func (a *TCPAddr) toLocal(net string) sockaddr

type TCPConn

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

type TCPConn struct {
    conn
}

func newTCPConn

func newTCPConn(fd *netFD) *TCPConn

func (*TCPConn) Close

func (c *TCPConn) Close() error

Close closes the connection.

func (*TCPConn) CloseRead

func (c *TCPConn) CloseRead() error

CloseRead shuts down the reading side of the TCP connection. Most callers should just use Close.

func (*TCPConn) CloseWrite

func (c *TCPConn) CloseWrite() error

CloseWrite shuts down the writing side of the TCP connection. Most callers should just use Close.

func (*TCPConn) File

func (c *TCPConn) File() (f *os.File, err error)

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.

func (*TCPConn) LocalAddr

func (c *TCPConn) LocalAddr() Addr

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

func (*TCPConn) Read

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

Read implements the Conn Read method.

func (*TCPConn) ReadFrom

func (c *TCPConn) ReadFrom(r io.Reader) (int64, error)

ReadFrom implements the io.ReaderFrom ReadFrom method.

func (*TCPConn) RemoteAddr

func (c *TCPConn) RemoteAddr() Addr

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

func (*TCPConn) SetDeadline

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

SetDeadline implements the Conn SetDeadline method.

func (*TCPConn) SetKeepAlive

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

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

func (*TCPConn) SetKeepAlivePeriod 1.2

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

SetKeepAlivePeriod sets period between keep-alives.

func (*TCPConn) SetLinger

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

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

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

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

If sec > 0, the data is sent in the background as with sec < 0. On some operating systems after sec seconds have elapsed any remaining unsent data may be discarded.

func (*TCPConn) SetNoDelay

func (c *TCPConn) SetNoDelay(noDelay bool) error

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.

func (*TCPConn) SetReadBuffer

func (c *TCPConn) SetReadBuffer(bytes int) error

SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

func (*TCPConn) SetReadDeadline

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

SetReadDeadline implements the Conn SetReadDeadline method.

func (*TCPConn) SetWriteBuffer

func (c *TCPConn) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

func (*TCPConn) SetWriteDeadline

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

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*TCPConn) SyscallConn 1.9

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

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

func (*TCPConn) Write

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

Write implements the Conn Write method.

func (*TCPConn) ok

func (c *TCPConn) ok() bool

func (*TCPConn) readFrom

func (c *TCPConn) readFrom(r io.Reader) (int64, error)

func (*TCPConn) writeBuffers

func (c *TCPConn) writeBuffers(v *Buffers) (int64, error)

type TCPListener

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

type TCPListener struct {
    fd *netFD
    lc ListenConfig
}

func (*TCPListener) Accept

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

Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn.

func (*TCPListener) AcceptTCP

func (l *TCPListener) AcceptTCP() (*TCPConn, error)

AcceptTCP accepts the next incoming call and returns the new connection.

func (*TCPListener) Addr

func (l *TCPListener) Addr() Addr

Addr returns the listener's network address, a *TCPAddr. The Addr returned is shared by all invocations of Addr, so do not modify it.

func (*TCPListener) Close

func (l *TCPListener) Close() error

Close stops listening on the TCP address. Already Accepted connections are not closed.

func (*TCPListener) File

func (l *TCPListener) File() (f *os.File, err error)

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.

func (*TCPListener) SetDeadline

func (l *TCPListener) SetDeadline(t time.Time) error

SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.

func (*TCPListener) SyscallConn 1.10

func (l *TCPListener) SyscallConn() (syscall.RawConn, error)

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.

func (*TCPListener) accept

func (ln *TCPListener) accept() (*TCPConn, error)

func (*TCPListener) close

func (ln *TCPListener) close() error

func (*TCPListener) file

func (ln *TCPListener) file() (*os.File, error)

func (*TCPListener) ok

func (ln *TCPListener) ok() bool

type UDPAddr

UDPAddr represents the address of a UDP end point.

type UDPAddr struct {
    IP   IP
    Port int
    Zone string // IPv6 scoped addressing zone; added in Go 1.1
}

func (*UDPAddr) Network

func (a *UDPAddr) Network() string

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

func (*UDPAddr) String

func (a *UDPAddr) String() string

func (*UDPAddr) family

func (a *UDPAddr) family() int

func (*UDPAddr) isWildcard

func (a *UDPAddr) isWildcard() bool

func (*UDPAddr) opAddr

func (a *UDPAddr) opAddr() Addr

func (*UDPAddr) sockaddr

func (a *UDPAddr) sockaddr(family int) (syscall.Sockaddr, error)

func (*UDPAddr) toLocal

func (a *UDPAddr) toLocal(net string) sockaddr

type UDPConn

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

type UDPConn struct {
    conn
}

func newUDPConn

func newUDPConn(fd *netFD) *UDPConn

func (*UDPConn) Close

func (c *UDPConn) Close() error

Close closes the connection.

func (*UDPConn) File

func (c *UDPConn) File() (f *os.File, err error)

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.

func (*UDPConn) LocalAddr

func (c *UDPConn) LocalAddr() Addr

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

func (*UDPConn) Read

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

Read implements the Conn Read method.

func (*UDPConn) ReadFrom

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

ReadFrom implements the PacketConn ReadFrom method.

func (*UDPConn) ReadFromUDP

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

ReadFromUDP acts like ReadFrom but returns a UDPAddr.

func (*UDPConn) ReadMsgUDP 1.1

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

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

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

func (*UDPConn) RemoteAddr

func (c *UDPConn) RemoteAddr() Addr

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

func (*UDPConn) SetDeadline

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

SetDeadline implements the Conn SetDeadline method.

func (*UDPConn) SetReadBuffer

func (c *UDPConn) SetReadBuffer(bytes int) error

SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

func (*UDPConn) SetReadDeadline

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

SetReadDeadline implements the Conn SetReadDeadline method.

func (*UDPConn) SetWriteBuffer

func (c *UDPConn) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

func (*UDPConn) SetWriteDeadline

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

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*UDPConn) SyscallConn 1.9

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

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

func (*UDPConn) Write

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

Write implements the Conn Write method.

func (*UDPConn) WriteMsgUDP 1.1

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

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

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

func (*UDPConn) WriteTo

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

WriteTo implements the PacketConn WriteTo method.

Example

func (*UDPConn) WriteToUDP

func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error)

WriteToUDP acts like WriteTo but takes a UDPAddr.

func (*UDPConn) ok

func (c *UDPConn) ok() bool

func (*UDPConn) readFrom

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

func (*UDPConn) readMsg

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

func (*UDPConn) writeBuffers

func (c *UDPConn) writeBuffers(v *Buffers) (int64, error)

func (*UDPConn) writeMsg

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

func (*UDPConn) writeTo

func (c *UDPConn) writeTo(b []byte, addr *UDPAddr) (int, error)

type UnixAddr

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

type UnixAddr struct {
    Name string
    Net  string
}

func (*UnixAddr) Network

func (a *UnixAddr) Network() string

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

func (*UnixAddr) String

func (a *UnixAddr) String() string

func (*UnixAddr) family

func (a *UnixAddr) family() int

func (*UnixAddr) isWildcard

func (a *UnixAddr) isWildcard() bool

func (*UnixAddr) opAddr

func (a *UnixAddr) opAddr() Addr

func (*UnixAddr) sockaddr

func (a *UnixAddr) sockaddr(family int) (syscall.Sockaddr, error)

func (*UnixAddr) toLocal

func (a *UnixAddr) toLocal(net string) sockaddr

type UnixConn

UnixConn is an implementation of the Conn interface for connections to Unix domain sockets.

type UnixConn struct {
    conn
}

func newUnixConn

func newUnixConn(fd *netFD) *UnixConn

func (*UnixConn) Close

func (c *UnixConn) Close() error

Close closes the connection.

func (*UnixConn) CloseRead 1.1

func (c *UnixConn) CloseRead() error

CloseRead shuts down the reading side of the Unix domain connection. Most callers should just use Close.

func (*UnixConn) CloseWrite 1.1

func (c *UnixConn) CloseWrite() error

CloseWrite shuts down the writing side of the Unix domain connection. Most callers should just use Close.

func (*UnixConn) File

func (c *UnixConn) File() (f *os.File, err error)

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.

func (*UnixConn) LocalAddr

func (c *UnixConn) LocalAddr() Addr

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

func (*UnixConn) Read

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

Read implements the Conn Read method.

func (*UnixConn) ReadFrom

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

ReadFrom implements the PacketConn ReadFrom method.

func (*UnixConn) ReadFromUnix

func (c *UnixConn) ReadFromUnix(b []byte) (int, *UnixAddr, error)

ReadFromUnix acts like ReadFrom but returns a UnixAddr.

func (*UnixConn) ReadMsgUnix

func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error)

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.

func (*UnixConn) RemoteAddr

func (c *UnixConn) RemoteAddr() Addr

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

func (*UnixConn) SetDeadline

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

SetDeadline implements the Conn SetDeadline method.

func (*UnixConn) SetReadBuffer

func (c *UnixConn) SetReadBuffer(bytes int) error

SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

func (*UnixConn) SetReadDeadline

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

SetReadDeadline implements the Conn SetReadDeadline method.

func (*UnixConn) SetWriteBuffer

func (c *UnixConn) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

func (*UnixConn) SetWriteDeadline

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

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*UnixConn) SyscallConn 1.9

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

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

func (*UnixConn) Write

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

Write implements the Conn Write method.

func (*UnixConn) WriteMsgUnix

func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err error)

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.

func (*UnixConn) WriteTo

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

WriteTo implements the PacketConn WriteTo method.

func (*UnixConn) WriteToUnix

func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (int, error)

WriteToUnix acts like WriteTo but takes a UnixAddr.

func (*UnixConn) ok

func (c *UnixConn) ok() bool

func (*UnixConn) readFrom

func (c *UnixConn) readFrom(b []byte) (int, *UnixAddr, error)

func (*UnixConn) readMsg

func (c *UnixConn) readMsg(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error)

func (*UnixConn) writeBuffers

func (c *UnixConn) writeBuffers(v *Buffers) (int64, error)

func (*UnixConn) writeMsg

func (c *UnixConn) writeMsg(b, oob []byte, addr *UnixAddr) (n, oobn int, err error)

func (*UnixConn) writeTo

func (c *UnixConn) writeTo(b []byte, addr *UnixAddr) (int, error)

type UnixListener

UnixListener is a Unix domain socket listener. Clients should typically use variables of type Listener instead of assuming Unix domain sockets.

type UnixListener struct {
    fd         *netFD
    path       string
    unlink     bool
    unlinkOnce sync.Once
}

func (*UnixListener) Accept

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

Accept implements the Accept method in the Listener interface. Returned connections will be of type *UnixConn.

func (*UnixListener) AcceptUnix

func (l *UnixListener) AcceptUnix() (*UnixConn, error)

AcceptUnix accepts the next incoming call and returns the new connection.

func (*UnixListener) Addr

func (l *UnixListener) Addr() Addr

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

func (*UnixListener) Close

func (l *UnixListener) Close() error

Close stops listening on the Unix address. Already accepted connections are not closed.

func (*UnixListener) File

func (l *UnixListener) File() (f *os.File, err error)

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.

func (*UnixListener) SetDeadline

func (l *UnixListener) SetDeadline(t time.Time) error

SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.

func (*UnixListener) SetUnlinkOnClose 1.8

func (l *UnixListener) SetUnlinkOnClose(unlink bool)

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.

func (*UnixListener) SyscallConn 1.10

func (l *UnixListener) SyscallConn() (syscall.RawConn, error)

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.

func (*UnixListener) accept

func (ln *UnixListener) accept() (*UnixConn, error)

func (*UnixListener) close

func (ln *UnixListener) close() error

func (*UnixListener) file

func (ln *UnixListener) file() (*os.File, error)

func (*UnixListener) ok

func (ln *UnixListener) ok() bool

type UnknownNetworkError

type UnknownNetworkError string

func (UnknownNetworkError) Error

func (e UnknownNetworkError) Error() string

func (UnknownNetworkError) Temporary

func (e UnknownNetworkError) Temporary() bool

func (UnknownNetworkError) Timeout

func (e UnknownNetworkError) Timeout() bool

type addrList

An addrList represents a list of network endpoint addresses.

type addrList []Addr

func (addrList) first

func (addrs addrList) first(strategy func(Addr) bool) Addr

first returns the first address which satisfies strategy, or if none do, then the first address of any kind.

func (addrList) forResolve

func (addrs addrList) forResolve(network, addr string) Addr

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.

func (addrList) partition

func (addrs addrList) partition(strategy func(Addr) bool) (primaries, fallbacks addrList)

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.

type addrinfoErrno

An addrinfoErrno represents a getaddrinfo, getnameinfo-specific error number. It's a signed number and a zero value is a non-error by convention.

type addrinfoErrno int

func (addrinfoErrno) Error

func (eai addrinfoErrno) Error() string

func (addrinfoErrno) Temporary

func (eai addrinfoErrno) Temporary() bool

func (addrinfoErrno) Timeout

func (eai addrinfoErrno) Timeout() bool

type buffersWriter

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.

type buffersWriter interface {
    writeBuffers(*Buffers) (int64, error)
}

type byMaskLength

byMaskLength sorts policyTableEntry by the size of their Prefix.Mask.Size, from smallest mask, to largest.

type byMaskLength []policyTableEntry

func (byMaskLength) Len

func (s byMaskLength) Len() int

func (byMaskLength) Less

func (s byMaskLength) Less(i, j int) bool

func (byMaskLength) Swap

func (s byMaskLength) Swap(i, j int)

type byPref

byPref implements sort.Interface to sort MX records by preference

type byPref []*MX

func (byPref) Len

func (s byPref) Len() int

func (byPref) Less

func (s byPref) Less(i, j int) bool

func (byPref) Swap

func (s byPref) Swap(i, j int)

func (byPref) sort

func (s byPref) sort()

sort reorders MX records as specified in RFC 5321.

type byPriorityWeight

byPriorityWeight sorts SRV records by ascending priority and weight.

type byPriorityWeight []*SRV

func (byPriorityWeight) Len

func (s byPriorityWeight) Len() int

func (byPriorityWeight) Less

func (s byPriorityWeight) Less(i, j int) bool

func (byPriorityWeight) Swap

func (s byPriorityWeight) Swap(i, j int)

func (byPriorityWeight) shuffleByWeight

func (addrs byPriorityWeight) shuffleByWeight()

shuffleByWeight shuffles SRV records by weight using the algorithm described in RFC 2782.

func (byPriorityWeight) sort

func (addrs byPriorityWeight) sort()

sort reorders SRV records as specified in RFC 2782.

type byRFC6724

type byRFC6724 struct {
    addrs    []IPAddr // addrs to sort
    addrAttr []ipAttr
    srcs     []IP // or nil if unreachable
    srcAttr  []ipAttr
}

func (*byRFC6724) Len

func (s *byRFC6724) Len() int

func (*byRFC6724) Less

func (s *byRFC6724) Less(i, j int) bool

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.

func (*byRFC6724) Swap

func (s *byRFC6724) Swap(i, j int)

type conf

conf represents a system's network configuration.

type conf struct {
    // forceCgoLookupHost forces CGO to always be used, if available.
    forceCgoLookupHost bool

    netGo  bool // go DNS resolution forced
    netCgo bool // cgo DNS resolution forced

    // machine has an /etc/mdns.allow file
    hasMDNSAllow bool

    goos          string // the runtime.GOOS, to ease testing
    dnsDebugLevel int

    nss    *nssConf
    resolv *dnsConfig
}

func systemConf

func systemConf() *conf

systemConf returns the machine's network configuration.

func (*conf) canUseCgo

func (c *conf) canUseCgo() bool

canUseCgo reports whether calling cgo functions is allowed for non-hostname lookups.

func (*conf) hostLookupOrder

func (c *conf) hostLookupOrder(r *Resolver, hostname string) (ret hostLookupOrder)

hostLookupOrder determines which strategy to use to resolve hostname. The provided Resolver is optional. nil means to not consider its options.

type conn

type conn struct {
    fd *netFD
}

func (*conn) Close

func (c *conn) Close() error

Close closes the connection.

func (*conn) File

func (c *conn) File() (f *os.File, err error)

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.

func (*conn) LocalAddr

func (c *conn) LocalAddr() Addr

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

func (*conn) Read

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

Read implements the Conn Read method.

func (*conn) RemoteAddr

func (c *conn) RemoteAddr() Addr

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

func (*conn) SetDeadline

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

SetDeadline implements the Conn SetDeadline method.

func (*conn) SetReadBuffer

func (c *conn) SetReadBuffer(bytes int) error

SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

func (*conn) SetReadDeadline

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

SetReadDeadline implements the Conn SetReadDeadline method.

func (*conn) SetWriteBuffer

func (c *conn) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

func (*conn) SetWriteDeadline

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

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*conn) Write

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

Write implements the Conn Write method.

func (*conn) ok

func (c *conn) ok() bool

func (*conn) writeBuffers

func (c *conn) writeBuffers(v *Buffers) (int64, error)

type dnsConfig

type dnsConfig struct {
    servers       []string      // server addresses (in host:port form) to use
    search        []string      // rooted suffixes to append to local name
    ndots         int           // number of dots in name to trigger absolute lookup
    timeout       time.Duration // wait before giving up on a query, including retries
    attempts      int           // lost packets before giving up on server
    rotate        bool          // round robin among servers
    unknownOpt    bool          // anything unknown was encountered
    lookup        []string      // OpenBSD top-level database "lookup" order
    err           error         // any error that occurs during open of resolv.conf
    mtime         time.Time     // time of resolv.conf modification
    soffset       uint32        // used by serverOffset
    singleRequest bool          // use sequential A and AAAA queries instead of parallel queries
    useTCP        bool          // force usage of TCP for DNS resolutions
}

func dnsReadConfig

func dnsReadConfig(filename string) *dnsConfig

See resolv.conf(5) on a Linux machine.

func (*dnsConfig) nameList

func (conf *dnsConfig) nameList(name string) []string

nameList returns a list of names for sequential DNS queries.

func (*dnsConfig) serverOffset

func (c *dnsConfig) serverOffset() uint32

serverOffset returns an offset that can be used to determine indices of servers in c.servers when making queries. When the rotate option is enabled, this offset increases. Otherwise it is always 0.

type file

type file struct {
    file  *os.File
    data  []byte
    atEOF bool
}

func (*file) close

func (f *file) close()

func (*file) getLineFromData

func (f *file) getLineFromData() (s string, ok bool)

func (*file) readLine

func (f *file) readLine() (s string, ok bool)

type fileAddr

type fileAddr string

func (fileAddr) Network

func (fileAddr) Network() string

func (fileAddr) String

func (f fileAddr) String() string

type hostLookupOrder

hostLookupOrder specifies the order of LookupHost lookup strategies. It is basically a simplified representation of nsswitch.conf. "files" means /etc/hosts.

type hostLookupOrder int
const (
    // hostLookupCgo means defer to cgo.
    hostLookupCgo      hostLookupOrder = iota
    hostLookupFilesDNS                 // files first
    hostLookupDNSFiles                 // dns first
    hostLookupFiles                    // only files
    hostLookupDNS                      // only DNS
)

func (hostLookupOrder) String

func (o hostLookupOrder) String() string

type ipAttr

type ipAttr struct {
    Scope      scope
    Precedence uint8
    Label      uint8
}

func ipAttrOf

func ipAttrOf(ip IP) ipAttr

type ipLookupResult

type ipLookupResult struct {
    addrs []IPAddr
    cname string
    err   error
}

type ipStackCapabilities

type ipStackCapabilities struct {
    sync.Once             // guards following
    ipv4Enabled           bool
    ipv6Enabled           bool
    ipv4MappedIPv6Enabled bool
}
var ipStackCaps ipStackCapabilities

func (*ipStackCapabilities) probe

func (p *ipStackCapabilities) probe()

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-mapeed 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.

type ipv6ZoneCache

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.

type ipv6ZoneCache struct {
    sync.RWMutex                // guard the following
    lastFetched  time.Time      // last time routing information was fetched
    toIndex      map[string]int // interface name to its index
    toName       map[int]string // interface index to its name
}

func (*ipv6ZoneCache) index

func (zc *ipv6ZoneCache) index(name string) int

func (*ipv6ZoneCache) name

func (zc *ipv6ZoneCache) name(index int) string

func (*ipv6ZoneCache) update

func (zc *ipv6ZoneCache) update(ift []Interface, force bool) (updated bool)

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.

type netFD

Network file descriptor.

type netFD struct {
    pfd poll.FD

    // immutable until Close
    family      int
    sotype      int
    isConnected bool // handshake completed or use of association with peer
    net         string
    laddr       Addr
    raddr       Addr
}

func (*netFD) Close

func (fd *netFD) Close() error

func (*netFD) Read

func (fd *netFD) Read(p []byte) (n int, err error)

func (*netFD) SetDeadline

func (fd *netFD) SetDeadline(t time.Time) error

func (*netFD) SetReadDeadline

func (fd *netFD) SetReadDeadline(t time.Time) error

func (*netFD) SetWriteDeadline

func (fd *netFD) SetWriteDeadline(t time.Time) error

func (*netFD) Write

func (fd *netFD) Write(p []byte) (nn int, err error)

func (*netFD) accept

func (fd *netFD) accept() (netfd *netFD, err error)

func (*netFD) addrFunc

func (fd *netFD) addrFunc() func(syscall.Sockaddr) Addr

func (*netFD) closeRead

func (fd *netFD) closeRead() error

func (*netFD) closeWrite

func (fd *netFD) closeWrite() error

func (*netFD) connect

func (fd *netFD) connect(ctx context.Context, la, ra syscall.Sockaddr) (rsa syscall.Sockaddr, ret error)

func (*netFD) ctrlNetwork

func (fd *netFD) ctrlNetwork() string

func (*netFD) dial

func (fd *netFD) dial(ctx context.Context, laddr, raddr sockaddr, ctrlFn func(string, string, syscall.RawConn) error) error

func (*netFD) dup

func (fd *netFD) dup() (f *os.File, err error)

func (*netFD) init

func (fd *netFD) init() error

func (*netFD) listenDatagram

func (fd *netFD) listenDatagram(laddr sockaddr, ctrlFn func(string, string, syscall.RawConn) error) error

func (*netFD) listenStream

func (fd *netFD) listenStream(laddr sockaddr, backlog int, ctrlFn func(string, string, syscall.RawConn) error) error

func (*netFD) name

func (fd *netFD) name() string

func (*netFD) readFrom

func (fd *netFD) readFrom(p []byte) (n int, sa syscall.Sockaddr, err error)

func (*netFD) readMsg

func (fd *netFD) readMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.Sockaddr, err error)

func (*netFD) setAddr

func (fd *netFD) setAddr(laddr, raddr Addr)

func (*netFD) shutdown

func (fd *netFD) shutdown(how int) error

func (*netFD) writeBuffers

func (fd *netFD) writeBuffers(v *Buffers) (n int64, err error)

func (*netFD) writeMsg

func (fd *netFD) writeMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err error)

func (*netFD) writeTo

func (fd *netFD) writeTo(p []byte, sa syscall.Sockaddr) (n int, err error)

type nssConf

nssConf represents the state of the machine's /etc/nsswitch.conf file.

type nssConf struct {
    err     error                  // any error encountered opening or parsing the file
    sources map[string][]nssSource // keyed by database (e.g. "hosts")
}

func parseNSSConf

func parseNSSConf(r io.Reader) *nssConf

func parseNSSConfFile

func parseNSSConfFile(file string) *nssConf

type nssCriterion

nssCriterion is the parsed structure of one of the criteria in brackets after an NSS source name.

type nssCriterion struct {
    negate bool   // if "!" was present
    status string // e.g. "success", "unavail" (lowercase)
    action string // e.g. "return", "continue" (lowercase)
}

func (nssCriterion) standardStatusAction

func (c nssCriterion) standardStatusAction(last bool) bool

standardStatusAction reports whether c is equivalent to not specifying the criterion at all. last is whether this criteria is the last in the list.

type nssSource

type nssSource struct {
    source   string // e.g. "compat", "files", "mdns4_minimal"
    criteria []nssCriterion
}

func (nssSource) standardCriteria

func (s nssSource) standardCriteria() bool

standardCriteria reports all specified criteria have the default status actions.

type onlyValuesCtx

onlyValuesCtx is a context that uses an underlying context for value lookup if the underlying context hasn't yet expired.

type onlyValuesCtx struct {
    context.Context
    lookupValues context.Context
}

func (*onlyValuesCtx) Value

func (ovc *onlyValuesCtx) Value(key interface{}) interface{}

Value performs a lookup if the original context hasn't expired.

type pipe

type pipe struct {
    wrMu sync.Mutex // Serialize Write operations

    // Used by local Read to interact with remote Write.
    // Successful receive on rdRx is always followed by send on rdTx.
    rdRx <-chan []byte
    rdTx chan<- int

    // Used by local Write to interact with remote Read.
    // Successful send on wrTx is always followed by receive on wrRx.
    wrTx chan<- []byte
    wrRx <-chan int

    once       sync.Once // Protects closing localDone
    localDone  chan struct{}
    remoteDone <-chan struct{}

    readDeadline  pipeDeadline
    writeDeadline pipeDeadline
}

func (*pipe) Close

func (p *pipe) Close() error

func (*pipe) LocalAddr

func (*pipe) LocalAddr() Addr

func (*pipe) Read

func (p *pipe) Read(b []byte) (int, error)

func (*pipe) RemoteAddr

func (*pipe) RemoteAddr() Addr

func (*pipe) SetDeadline

func (p *pipe) SetDeadline(t time.Time) error

func (*pipe) SetReadDeadline

func (p *pipe) SetReadDeadline(t time.Time) error

func (*pipe) SetWriteDeadline

func (p *pipe) SetWriteDeadline(t time.Time) error

func (*pipe) Write

func (p *pipe) Write(b []byte) (int, error)

func (*pipe) read

func (p *pipe) read(b []byte) (n int, err error)

func (*pipe) write

func (p *pipe) write(b []byte) (n int, err error)

type pipeAddr

type pipeAddr struct{}

func (pipeAddr) Network

func (pipeAddr) Network() string

func (pipeAddr) String

func (pipeAddr) String() string

type pipeDeadline

pipeDeadline is an abstraction for handling timeouts.

type pipeDeadline struct {
    mu     sync.Mutex // Guards timer and cancel
    timer  *time.Timer
    cancel chan struct{} // Must be non-nil
}

func makePipeDeadline

func makePipeDeadline() pipeDeadline

func (*pipeDeadline) set

func (d *pipeDeadline) set(t time.Time)

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.

func (*pipeDeadline) wait

func (d *pipeDeadline) wait() chan struct{}

wait returns a channel that is closed when the deadline is exceeded.

type policyTable

type policyTable []policyTableEntry

func (policyTable) Classify

func (t policyTable) Classify(ip IP) policyTableEntry

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.

type policyTableEntry

type policyTableEntry struct {
    Prefix     *IPNet
    Precedence uint8
    Label      uint8
}

type portLookupResult

type portLookupResult struct {
    port int
    err  error
}

type rawConn

type rawConn struct {
    fd *netFD
}

func (*rawConn) Control

func (c *rawConn) Control(f func(uintptr)) error

func (*rawConn) Read

func (c *rawConn) Read(f func(uintptr) bool) error

func (*rawConn) Write

func (c *rawConn) Write(f func(uintptr) bool) error

func (*rawConn) ok

func (c *rawConn) ok() bool

type rawListener

type rawListener struct {
    rawConn
}

func (*rawListener) Control

func (c *rawListener) Control(f func(uintptr)) error

func (*rawListener) Read

func (l *rawListener) Read(func(uintptr) bool) error

func (*rawListener) Write

func (l *rawListener) Write(func(uintptr) bool) error

func (*rawListener) ok

func (c *rawListener) ok() bool

type resolverConfig

A resolverConfig represents a DNS stub resolver configuration.

type resolverConfig struct {
    initOnce sync.Once // guards init of resolverConfig

    // ch is used as a semaphore that only allows one lookup at a
    // time to recheck resolv.conf.
    ch          chan struct{} // guards lastChecked and modTime
    lastChecked time.Time     // last time resolv.conf was checked

    mu        sync.RWMutex // protects dnsConfig
    dnsConfig *dnsConfig   // parsed resolv.conf structure used in lookups
}
var resolvConf resolverConfig

func (*resolverConfig) init

func (conf *resolverConfig) init()

init initializes conf and is only called via conf.initOnce.

func (*resolverConfig) releaseSema

func (conf *resolverConfig) releaseSema()

func (*resolverConfig) tryAcquireSema

func (conf *resolverConfig) tryAcquireSema() bool

func (*resolverConfig) tryUpdate

func (conf *resolverConfig) tryUpdate(name string)

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".

type reverseLookupResult

type reverseLookupResult struct {
    names []string
    err   error
}

type scope

RFC 6724 section 3.1.

type scope uint8
const (
    scopeInterfaceLocal scope = 0x1
    scopeLinkLocal      scope = 0x2
    scopeAdminLocal     scope = 0x4
    scopeSiteLocal      scope = 0x5
    scopeOrgLocal       scope = 0x8
    scopeGlobal         scope = 0xe
)

func classifyScope

func classifyScope(ip IP) scope

type sockaddr

A sockaddr represents a TCP, UDP, IP or Unix network endpoint address that can be converted into a syscall.Sockaddr.

type sockaddr interface {
    Addr

    // family returns the platform-dependent address family
    // identifier.
    family() int

    // isWildcard reports whether the address is a wildcard
    // address.
    isWildcard() bool

    // sockaddr returns the address converted into a syscall
    // sockaddr type that implements syscall.Sockaddr
    // interface. It returns a nil interface when the address is
    // nil.
    sockaddr(family int) (syscall.Sockaddr, error)

    // toLocal maps the zero address to a local system address (127.0.0.1 or ::1)
    toLocal(net string) sockaddr
}

type sysDialer

sysDialer contains a Dial's parameters and configuration.

type sysDialer struct {
    Dialer
    network, address string
}

func (*sysDialer) dialIP

func (sd *sysDialer) dialIP(ctx context.Context, laddr, raddr *IPAddr) (*IPConn, error)

func (*sysDialer) dialParallel

func (sd *sysDialer) dialParallel(ctx context.Context, primaries, fallbacks addrList) (Conn, 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.

func (*sysDialer) dialSerial

func (sd *sysDialer) dialSerial(ctx context.Context, ras addrList) (Conn, error)

dialSerial connects to a list of addresses in sequence, returning either the first successful connection, or the first error.

func (*sysDialer) dialSingle

func (sd *sysDialer) dialSingle(ctx context.Context, ra Addr) (c Conn, err error)

dialSingle attempts to establish and returns a single connection to the destination address.

func (*sysDialer) dialTCP

func (sd *sysDialer) dialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error)

func (*sysDialer) dialUDP

func (sd *sysDialer) dialUDP(ctx context.Context, laddr, raddr *UDPAddr) (*UDPConn, error)

func (*sysDialer) dialUnix

func (sd *sysDialer) dialUnix(ctx context.Context, laddr, raddr *UnixAddr) (*UnixConn, error)

func (*sysDialer) doDialTCP

func (sd *sysDialer) doDialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error)

type sysListener

sysListener contains a Listen's parameters and configuration.

type sysListener struct {
    ListenConfig
    network, address string
}

func (*sysListener) listenIP

func (sl *sysListener) listenIP(ctx context.Context, laddr *IPAddr) (*IPConn, error)

func (*sysListener) listenMulticastUDP

func (sl *sysListener) listenMulticastUDP(ctx context.Context, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)

func (*sysListener) listenTCP

func (sl *sysListener) listenTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error)

func (*sysListener) listenUDP

func (sl *sysListener) listenUDP(ctx context.Context, laddr *UDPAddr) (*UDPConn, error)

func (*sysListener) listenUnix

func (sl *sysListener) listenUnix(ctx context.Context, laddr *UnixAddr) (*UnixListener, error)

func (*sysListener) listenUnixgram

func (sl *sysListener) listenUnixgram(ctx context.Context, laddr *UnixAddr) (*UnixConn, error)

type temporary

type temporary interface {
    Temporary() bool
}

type timeout

type timeout interface {
    Timeout() bool
}

type timeoutError

type timeoutError struct{}

func (*timeoutError) Error

func (e *timeoutError) Error() string

func (*timeoutError) Temporary

func (e *timeoutError) Temporary() bool

func (*timeoutError) Timeout

func (e *timeoutError) Timeout() bool

type writerOnly

type writerOnly struct {
    io.Writer
}

Bugs

Subdirectories

Name Synopsis
..
http Package http provides HTTP client and server implementations.
cgi Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
cookiejar Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
fcgi Package fcgi implements the FastCGI protocol.
httptest Package httptest provides utilities for HTTP testing.
httptrace Package httptrace provides mechanisms to trace the events within HTTP client requests.
httputil Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package.
internal Package internal contains HTTP internals shared by net/http and net/http/httputil.
pprof Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
internal
socktest Package socktest provides utilities for socket testing.
mail Package mail implements parsing of mail messages.
rpc Package rpc provides access to the exported methods of an object across a network or other I/O connection.
jsonrpc Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package.
smtp Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
textproto Package textproto implements generic support for text-based request/response protocols in the style of HTTP, NNTP, and SMTP.
url Package url parses URLs and implements query escaping.