Movatterモバイル変換


[0]ホーム

URL:


net

packagestandard library
go1.24.1Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2025 License:BSD-3-ClauseImports:24Imported by:587,186

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package net provides a portable interface for network I/O, includingTCP/IP, UDP, domain name resolution, and Unix domain sockets.

Although the package provides access to low-level networkingprimitives, most clients will need only the basic interface providedby theDial,Listen, and Accept functions and the associatedConn andListener interfaces. The crypto/tls package usesthe 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 Dialor directly with functions likeLookupHost andLookupAddr, 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 serverslisted in /etc/resolv.conf, or it can use a cgo-based resolver that calls Clibrary routines such as getaddrinfo and getnameinfo.

On Unix the pure Go resolver is preferred over the cgo resolver, because a blocked DNSrequest 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 ofconditions: 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 theGo resolver does not implement.

On all systems (except Plan 9), when the cgo resolver is being usedthis package applies a concurrent cgo lookup limit to prevent the systemfrom running out of system threads. Currently, it is limited to 500 concurrent lookups.

The resolver decision can be overridden by setting the netdns value of theGODEBUG environment variable (see package runtime) to go or cgo, as in:

export GODEBUG=netdns=go    # force pure Go resolverexport GODEBUG=netdns=cgo   # force native resolver (cgo, win32)

The decision can also be forced while building the Go source treeby setting the netgo or netcgo build tag.The netgo build tag disables entirely the use of the native (CGO) resolver,meaning the Go resolver is the only one that can be used.With the netcgo build tag the native and the pure Go resolver are compiled into the binary,but the native (CGO) resolver is preferred over the Go resolver.With netcgo, the Go resolver can still be forced at runtime with GODEBUG=netdns=go.

A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolverto 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.

The Go resolver will send an EDNS0 additional header with a DNS request,to signal a willingness to accept a larger DNS packet size.This can reportedly cause sporadic failures with the DNS server runby some modems and routers. Setting GODEBUG=netedns0=0 will disablesending the additional header.

On macOS, if Go code that uses the net package is built with-buildmode=c-archive, linking the resulting archive into a C programrequires passing -lresolv when linking the C code.

On Plan 9, the resolver always accesses /net/cs and /net/dns.

On Windows, in Go 1.18.x and earlier, the resolver always used Clibrary functions, such as GetAddrInfo and DnsQuery.

Index

Examples

Constants

View Source
const (IPv4len = 4IPv6len = 16)

IP address lengths (bytes).

Variables

View Source
var (IPv4bcast     =IPv4(255, 255, 255, 255)// limited broadcastIPv4allsys    =IPv4(224, 0, 0, 1)// all systemsIPv4allrouter =IPv4(224, 0, 0, 2)// all routersIPv4zero      =IPv4(0, 0, 0, 0)// all zeros)

Well-known IPv4 addresses

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

Well-known IPv6 addresses

View Source
var DefaultResolver = &Resolver{}

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

View Source
var ErrClosederror = errClosed

ErrClosed is the error returned by an I/O call on a networkconnection that has already been closed, or that is closed byanother goroutine before the I/O is completed. This may be wrappedin another error, and should normally be tested usingerrors.Is(err, net.ErrClosed).

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

Various errors contained in OpError.

Functions

funcJoinHostPort

func JoinHostPort(host, portstring)string

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

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

funcLookupAddr

func LookupAddr(addrstring) (names []string, errerror)

LookupAddr performs a reverse lookup for the given address, returning a listof names mapping to that address.

The returned names are validated to be properly formatted presentation-formatdomain names. If the response contains invalid names, those records are filteredout and an error will be returned alongside the remaining results, if any.

When using the host C library resolver, at most one result will bereturned. To bypass the host resolver, use a customResolver.

LookupAddr usescontext.Background internally; to specify the context, useResolver.LookupAddr.

funcLookupCNAME

func LookupCNAME(hoststring) (cnamestring, errerror)

LookupCNAME returns the canonical name for the given host.Callers that do not care about the canonical name can callLookupHost orLookupIP directly; both take care of resolvingthe canonical name as part of the lookup.

A canonical name is the final name after following zeroor more CNAME records.LookupCNAME does not return an error if host does notcontain DNS "CNAME" records, as long as host resolves toaddress records.

The returned canonical name is validated to be a properlyformatted presentation-format domain name.

LookupCNAME usescontext.Background internally; to specify the context, useResolver.LookupCNAME.

funcLookupHost

func LookupHost(hoststring) (addrs []string, errerror)

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

LookupHost usescontext.Background internally; to specify the context, useResolver.LookupHost.

funcLookupPort

func LookupPort(network, servicestring) (portint, errerror)

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

LookupPort usescontext.Background internally; to specify the context, useResolver.LookupPort.

funcLookupTXT

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

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

If a DNS TXT record holds multiple strings, they are concatenated as asingle string.

LookupTXT usescontext.Background internally; to specify the context, useResolver.LookupTXT.

funcParseCIDR

func ParseCIDR(sstring) (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 inRFC 4632 andRFC 4291.

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

Example
package mainimport ("fmt""log""net")func main() {ipv4Addr, ipv4Net, err := net.ParseCIDR("192.0.2.1/24")if err != nil {log.Fatal(err)}fmt.Println(ipv4Addr)fmt.Println(ipv4Net)ipv6Addr, ipv6Net, err := net.ParseCIDR("2001:db8:a0b:12f0::1/32")if err != nil {log.Fatal(err)}fmt.Println(ipv6Addr)fmt.Println(ipv6Net)}
Output:192.0.2.1192.0.2.0/242001:db8:a0b:12f0::12001:db8::/32

funcPipe

func Pipe() (Conn,Conn)

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

funcSplitHostPort

func SplitHostPort(hostportstring) (host, portstring, errerror)

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

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

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

Types

typeAddr

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

Addr represents a network end point address.

The two methods [Addr.Network] and [Addr.String] conventionally return stringsthat can be passed as the arguments toDial, but the exact formand meaning of the strings is up to the implementation.

funcInterfaceAddrs

func InterfaceAddrs() ([]Addr,error)

InterfaceAddrs returns a list of the system's unicast interfaceaddresses.

The returned list does not identify the associated interface; useInterfaces andInterface.Addrs for more detail.

typeAddrError

type AddrError struct {ErrstringAddrstring}

func (*AddrError)Error

func (e *AddrError) Error()string

func (*AddrError)Temporary

func (e *AddrError) Temporary()bool

func (*AddrError)Timeout

func (e *AddrError) Timeout()bool

typeBuffersadded ingo1.8

type Buffers [][]byte

Buffers contains zero or more runs of bytes to write.

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

func (*Buffers)Readadded ingo1.8

func (v *Buffers) Read(p []byte) (nint, errerror)

Read from the buffers.

Read implementsio.Reader forBuffers.

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

func (*Buffers)WriteToadded ingo1.8

func (v *Buffers) WriteTo(wio.Writer) (nint64, errerror)

WriteTo writes contents of the buffers to w.

WriteTo implementsio.WriterTo forBuffers.

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

typeConn

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

Conn is a generic stream-oriented network connection.

Multiple goroutines may invoke methods on a Conn simultaneously.

funcDial

func Dial(network, addressstring) (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 beresolved 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 squarebrackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80".The zone specifies the scope of the literal IPv6 address as definedinRFC 4007.The functionsJoinHostPort andSplitHostPort manipulate a pair ofhost 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" followedby a colon and a literal protocol number or a protocol name, andthe address has the form "host". The host must be a literal IPaddress or a literal IPv6 address with zone.It depends on each operating system how the operating systembehaves 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 literalunspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" forTCP and UDP, "", "0.0.0.0" or "::" for IP, the local system isassumed.

For Unix networks, the address must be a file system path.

funcDialTimeout

func DialTimeout(network, addressstring, timeouttime.Duration) (Conn,error)

DialTimeout acts likeDial but takes a timeout.

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

See func Dial for a description of the network and addressparameters.

funcFileConn

func FileConn(f *os.File) (cConn, errerror)

FileConn returns a copy of the network connection corresponding tothe 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.

typeDNSConfigError

type DNSConfigError struct {Errerror}

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

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)Unwrapadded ingo1.13

func (e *DNSConfigError) Unwrap()error

typeDNSError

type DNSError struct {UnwrapErrerror// error returned by the [DNSError.Unwrap] method, might be nilErrstring// description of the errorNamestring// name looked forServerstring// server usedIsTimeoutbool// if true, timed out; not all timeouts set thisIsTemporarybool// if true, error is temporary; not all errors set this// IsNotFound is set to true when the requested name does not// contain any records of the requested type (data not found),// or the name itself was not found (NXDOMAIN).IsNotFoundbool}

DNSError represents a DNS lookup error.

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 temporaryerror and return aDNSError 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 timeoutand return aDNSError for which Timeout returns false.

func (*DNSError)Unwrapadded ingo1.23.0

func (e *DNSError) Unwrap()error

Unwrap returns e.UnwrapErr.

typeDialeradded ingo1.1

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.Timeouttime.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.Deadlinetime.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.LocalAddrAddr// DualStack previously enabledRFC 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.DualStackbool// FallbackDelay specifies the length of time to wait before// spawning aRFC 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.FallbackDelaytime.Duration// KeepAlive specifies the interval between keep-alive// probes for an active network connection.//// KeepAlive is ignored if KeepAliveConfig.Enable is true.//// 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-alive ignore this field.// If negative, keep-alive probes are disabled.KeepAlivetime.Duration// KeepAliveConfig specifies the keep-alive probe configuration// for an active network connection, when supported by the// protocol and operating system.//// If KeepAliveConfig.Enable is true, keep-alive probes are enabled.// If KeepAliveConfig.Enable is false and KeepAlive is negative,// keep-alive probes are disabled.KeepAliveConfigKeepAliveConfig// Resolver optionally specifies an alternate resolver to use.Resolver *Resolver// 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{}// If Control is not nil, it is called after creating the network// connection but before actually dialing.//// Network and address parameters passed to Control function are not// necessarily the ones passed to Dial. Calling Dial with TCP networks// will cause the Control function to be called with "tcp4" or "tcp6",// UDP networks become "udp4" or "udp6", IP networks become "ip4" or "ip6",// and other known networks are passed as-is.//// Control is ignored if ControlContext is not nil.Control func(network, addressstring, csyscall.RawConn)error// If ControlContext is not nil, it is called after creating the network// connection but before actually dialing.//// Network and address parameters passed to ControlContext function are not// necessarily the ones passed to Dial. Calling Dial with TCP networks// will cause the ControlContext function to be called with "tcp4" or "tcp6",// UDP networks become "udp4" or "udp6", IP networks become "ip4" or "ip6",// and other known networks are passed as-is.//// If ControlContext is not nil, Control is ignored.ControlContext func(ctxcontext.Context, network, addressstring, csyscall.RawConn)error// contains filtered or unexported fields}

A Dialer contains options for connecting to an address.

The zero value for each field is equivalent to dialingwithout that option. Dialing with the zero value of Dialeris therefore equivalent to just calling theDial function.

It is safe to call Dialer's methods concurrently.

Example
package mainimport ("context""log""net""time")func main() {var d net.Dialerctx, cancel := context.WithTimeout(context.Background(), time.Minute)defer cancel()conn, err := d.DialContext(ctx, "tcp", "localhost:12345")if err != nil {log.Fatalf("Failed to dial: %v", err)}defer conn.Close()if _, err := conn.Write([]byte("Hello, World!")); err != nil {log.Fatal(err)}}
Output:

Example (Unix)
package mainimport ("context""log""net""time")func main() {// DialUnix does not take a context.Context parameter. This example shows// how to dial a Unix socket with a Context. Note that the Context only// applies to the dial operation; it does not apply to the connection once// it has been established.var d net.Dialerctx, cancel := context.WithTimeout(context.Background(), time.Minute)defer cancel()d.LocalAddr = nil // if you have a local addr, add it hereraddr := net.UnixAddr{Name: "/path/to/unix.sock", Net: "unix"}conn, err := d.DialContext(ctx, "unix", raddr.String())if err != nil {log.Fatalf("Failed to dial: %v", err)}defer conn.Close()if _, err := conn.Write([]byte("Hello, socket!")); err != nil {log.Fatal(err)}}
Output:

func (*Dialer)Dialadded ingo1.1

func (d *Dialer) Dial(network, addressstring) (Conn,error)

Dial connects to the address on the named network.

See func Dial for a description of the network and addressparameters.

Dial usescontext.Background internally; to specify the context, useDialer.DialContext.

func (*Dialer)DialContextadded ingo1.7

func (d *Dialer) DialContext(ctxcontext.Context, network, addressstring) (Conn,error)

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

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

When using TCP, and the host in the address parameter resolves to multiplenetwork addresses, any dial timeout (from d.Timeout or ctx) is spreadover each consecutive dial, such that each is given an appropriatefraction 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 completebefore trying the next one.

See funcDial for a description of the network and addressparameters.

func (*Dialer)MultipathTCPadded ingo1.21.0

func (d *Dialer) MultipathTCP()bool

MultipathTCP reports whether MPTCP will be used.

This method doesn't check if MPTCP is supported by the operatingsystem or not.

func (*Dialer)SetMultipathTCPadded ingo1.21.0

func (d *Dialer) SetMultipathTCP(usebool)

SetMultipathTCP directs theDial methods to use, or not use, MPTCP,if supported by the operating system. This method overrides thesystem default and the GODEBUG=multipathtcp=... setting if any.

If MPTCP is not available on the host or not supported by the server,the Dial methods will fall back to TCP.

typeError

type Error interface {errorTimeout()bool// Is the error a timeout?// Deprecated: Temporary errors are not well-defined.// Most "temporary" errors are timeouts, and the few exceptions are surprising.// Do not use this method.Temporary()bool}

An Error represents a network error.

typeFlags

type Flagsuint
const (FlagUpFlags = 1 <<iota// interface is administratively upFlagBroadcast// interface supports broadcast access capabilityFlagLoopback// interface is a loopback interfaceFlagPointToPoint// interface belongs to a point-to-point linkFlagMulticast// interface supports multicast access capabilityFlagRunning// interface is in running state)

func (Flags)String

func (fFlags) String()string

typeHardwareAddr

type HardwareAddr []byte

A HardwareAddr represents a physical hardware address.

funcParseMAC

func ParseMAC(sstring) (hwHardwareAddr, errerror)

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

00:00:5e:00:53:0102:00:5e:10:00:00:00:0100:00:00:00:fe:80:00:00:00:00:00:00:02:00:5e:10:00:00:00:0100-00-5e-00-53-0102-00-5e-10-00-00-00-0100-00-00-00-fe-80-00-00-00-00-00-00-02-00-5e-10-00-00-00-010000.5e00.53010200.5e10.0000.00010000.0000.fe80.0000.0000.0000.0200.5e10.0000.0001

func (HardwareAddr)String

func (aHardwareAddr) String()string

typeIP

type IP []byte

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

Note that in this documentation, referring to anIP address as an IPv4 address or an IPv6 addressis a semantic property of the address, not just thelength of the byte slice: a 16-byte slice can stillbe an IPv4 address.

funcIPv4

func IPv4(a, b, c, dbyte)IP

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

Example
package mainimport ("fmt""net")func main() {fmt.Println(net.IPv4(8, 8, 8, 8))}
Output:8.8.8.8

funcLookupIP

func LookupIP(hoststring) ([]IP,error)

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

funcParseIP

func ParseIP(sstring)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. The returned address is always 16 bytes,IPv4 addresses are returned in IPv4-mapped IPv6 form.

Example
package mainimport ("fmt""net")func main() {fmt.Println(net.ParseIP("192.0.2.1"))fmt.Println(net.ParseIP("2001:db8::68"))fmt.Println(net.ParseIP("192.0.2"))}
Output:192.0.2.12001:db8::68<nil>

func (IP)AppendTextadded ingo1.24.0

func (ipIP) AppendText(b []byte) ([]byte,error)

AppendText implements theencoding.TextAppender interface.The encoding is the same as returned byIP.String, with one exception:When len(ip) is zero, it appends nothing.

func (IP)DefaultMask

func (ipIP) DefaultMask()IPMask

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

Example
package mainimport ("fmt""net")func main() {ip := net.ParseIP("192.0.2.1")fmt.Println(ip.DefaultMask())}
Output:ffffff00

func (IP)Equal

func (ipIP) Equal(xIP)bool

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

Example
package mainimport ("fmt""net")func main() {ipv4DNS := net.ParseIP("8.8.8.8")ipv4Lo := net.ParseIP("127.0.0.1")ipv6DNS := net.ParseIP("0:0:0:0:0:FFFF:0808:0808")fmt.Println(ipv4DNS.Equal(ipv4DNS))fmt.Println(ipv4DNS.Equal(ipv4Lo))fmt.Println(ipv4DNS.Equal(ipv6DNS))}
Output:truefalsetrue

func (IP)IsGlobalUnicast

func (ipIP) IsGlobalUnicast()bool

IsGlobalUnicast reports whether ip is a global unicastaddress.

The identification of global unicast addresses uses address typeidentification as defined inRFC 1122,RFC 4632 andRFC 4291 withthe exception of IPv4 directed broadcast addresses.It returns true even if ip is in IPv4 private address space orlocal IPv6 unicast address space.

Example
package mainimport ("fmt""net")func main() {ipv6Global := net.ParseIP("2000::")ipv6UniqLocal := net.ParseIP("2000::")ipv6Multi := net.ParseIP("FF00::")ipv4Private := net.ParseIP("10.255.0.0")ipv4Public := net.ParseIP("8.8.8.8")ipv4Broadcast := net.ParseIP("255.255.255.255")fmt.Println(ipv6Global.IsGlobalUnicast())fmt.Println(ipv6UniqLocal.IsGlobalUnicast())fmt.Println(ipv6Multi.IsGlobalUnicast())fmt.Println(ipv4Private.IsGlobalUnicast())fmt.Println(ipv4Public.IsGlobalUnicast())fmt.Println(ipv4Broadcast.IsGlobalUnicast())}
Output:truetruefalsetruetruefalse

func (IP)IsInterfaceLocalMulticast

func (ipIP) IsInterfaceLocalMulticast()bool

IsInterfaceLocalMulticast reports whether ip isan interface-local multicast address.

Example
package mainimport ("fmt""net")func main() {ipv6InterfaceLocalMulti := net.ParseIP("ff01::1")ipv6Global := net.ParseIP("2000::")ipv4 := net.ParseIP("255.0.0.0")fmt.Println(ipv6InterfaceLocalMulti.IsInterfaceLocalMulticast())fmt.Println(ipv6Global.IsInterfaceLocalMulticast())fmt.Println(ipv4.IsInterfaceLocalMulticast())}
Output:truefalsefalse

func (IP)IsLinkLocalMulticast

func (ipIP) IsLinkLocalMulticast()bool

IsLinkLocalMulticast reports whether ip is a link-localmulticast address.

Example
package mainimport ("fmt""net")func main() {ipv6LinkLocalMulti := net.ParseIP("ff02::2")ipv6LinkLocalUni := net.ParseIP("fe80::")ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")ipv4LinkLocalUni := net.ParseIP("169.254.0.0")fmt.Println(ipv6LinkLocalMulti.IsLinkLocalMulticast())fmt.Println(ipv6LinkLocalUni.IsLinkLocalMulticast())fmt.Println(ipv4LinkLocalMulti.IsLinkLocalMulticast())fmt.Println(ipv4LinkLocalUni.IsLinkLocalMulticast())}
Output:truefalsetruefalse

func (IP)IsLinkLocalUnicast

func (ipIP) IsLinkLocalUnicast()bool

IsLinkLocalUnicast reports whether ip is a link-localunicast address.

Example
package mainimport ("fmt""net")func main() {ipv6LinkLocalUni := net.ParseIP("fe80::")ipv6Global := net.ParseIP("2000::")ipv4LinkLocalUni := net.ParseIP("169.254.0.0")ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")fmt.Println(ipv6LinkLocalUni.IsLinkLocalUnicast())fmt.Println(ipv6Global.IsLinkLocalUnicast())fmt.Println(ipv4LinkLocalUni.IsLinkLocalUnicast())fmt.Println(ipv4LinkLocalMulti.IsLinkLocalUnicast())}
Output:truefalsetruefalse

func (IP)IsLoopback

func (ipIP) IsLoopback()bool

IsLoopback reports whether ip is a loopback address.

Example
package mainimport ("fmt""net")func main() {ipv6Lo := net.ParseIP("::1")ipv6 := net.ParseIP("ff02::1")ipv4Lo := net.ParseIP("127.0.0.0")ipv4 := net.ParseIP("128.0.0.0")fmt.Println(ipv6Lo.IsLoopback())fmt.Println(ipv6.IsLoopback())fmt.Println(ipv4Lo.IsLoopback())fmt.Println(ipv4.IsLoopback())}
Output:truefalsetruefalse

func (IP)IsMulticast

func (ipIP) IsMulticast()bool

IsMulticast reports whether ip is a multicast address.

Example
package mainimport ("fmt""net")func main() {ipv6Multi := net.ParseIP("FF00::")ipv6LinkLocalMulti := net.ParseIP("ff02::1")ipv6Lo := net.ParseIP("::1")ipv4Multi := net.ParseIP("239.0.0.0")ipv4LinkLocalMulti := net.ParseIP("224.0.0.0")ipv4Lo := net.ParseIP("127.0.0.0")fmt.Println(ipv6Multi.IsMulticast())fmt.Println(ipv6LinkLocalMulti.IsMulticast())fmt.Println(ipv6Lo.IsMulticast())fmt.Println(ipv4Multi.IsMulticast())fmt.Println(ipv4LinkLocalMulti.IsMulticast())fmt.Println(ipv4Lo.IsMulticast())}
Output:truetruefalsetruetruefalse

func (IP)IsPrivateadded ingo1.17

func (ipIP) IsPrivate()bool

IsPrivate reports whether ip is a private address, according toRFC 1918 (IPv4 addresses) andRFC 4193 (IPv6 addresses).

Example
package mainimport ("fmt""net")func main() {ipv6Private := net.ParseIP("fc00::")ipv6Public := net.ParseIP("fe00::")ipv4Private := net.ParseIP("10.255.0.0")ipv4Public := net.ParseIP("11.0.0.0")fmt.Println(ipv6Private.IsPrivate())fmt.Println(ipv6Public.IsPrivate())fmt.Println(ipv4Private.IsPrivate())fmt.Println(ipv4Public.IsPrivate())}
Output:truefalsetruefalse

func (IP)IsUnspecified

func (ipIP) IsUnspecified()bool

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

Example
package mainimport ("fmt""net")func main() {ipv6Unspecified := net.ParseIP("::")ipv6Specified := net.ParseIP("fe00::")ipv4Unspecified := net.ParseIP("0.0.0.0")ipv4Specified := net.ParseIP("8.8.8.8")fmt.Println(ipv6Unspecified.IsUnspecified())fmt.Println(ipv6Specified.IsUnspecified())fmt.Println(ipv4Unspecified.IsUnspecified())fmt.Println(ipv4Specified.IsUnspecified())}
Output:truefalsetruefalse

func (IP)MarshalTextadded ingo1.2

func (ipIP) MarshalText() ([]byte,error)

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

func (IP)Mask

func (ipIP) Mask(maskIPMask)IP

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

Example
package mainimport ("fmt""net")func main() {ipv4Addr := net.ParseIP("192.0.2.1")// This mask corresponds to a /24 subnet for IPv4.ipv4Mask := net.CIDRMask(24, 32)fmt.Println(ipv4Addr.Mask(ipv4Mask))ipv6Addr := net.ParseIP("2001:db8:a0b:12f0::1")// This mask corresponds to a /32 subnet for IPv6.ipv6Mask := net.CIDRMask(32, 128)fmt.Println(ipv6Addr.Mask(ipv6Mask))}
Output:192.0.2.02001:db8::

func (IP)String

func (ipIP) String()string

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

  • "<nil>", if ip has length 0
  • dotted decimal ("192.0.2.1"), if ip is an IPv4 or IP4-mapped IPv6 address
  • IPv6 conforming toRFC 5952 ("2001:db8::1"), if ip is a valid IPv6 address
  • the hexadecimal form of ip, without punctuation, if no other cases apply
Example
package mainimport ("fmt""net")func main() {ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}ipv4 := net.IPv4(10, 255, 0, 0)fmt.Println(ipv6.String())fmt.Println(ipv4.String())}
Output:fc00::10.255.0.0

func (IP)To16

func (ipIP) 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.

Example
package mainimport ("fmt""net")func main() {ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}ipv4 := net.IPv4(10, 255, 0, 0)fmt.Println(ipv6.To16())fmt.Println(ipv4.To16())}
Output:fc00::10.255.0.0

func (IP)To4

func (ipIP) To4()IP

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

Example
package mainimport ("fmt""net")func main() {ipv6 := net.IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}ipv4 := net.IPv4(10, 255, 0, 0)fmt.Println(ipv6.To4())fmt.Println(ipv4.To4())}
Output:<nil>10.255.0.0

func (*IP)UnmarshalTextadded ingo1.2

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

UnmarshalText implements theencoding.TextUnmarshaler interface.The IP address is expected in a form accepted byParseIP.

typeIPAddr

type IPAddr struct {IPIPZonestring// IPv6 scoped addressing zone}

IPAddr represents the address of an IP end point.

funcResolveIPAddr

func ResolveIPAddr(network, addressstring) (*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 notrecommended, because it will return at most one of the host name'sIP addresses.

See funcDial for a description of the network and addressparameters.

func (*IPAddr)Network

func (a *IPAddr) Network()string

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

func (*IPAddr)String

func (a *IPAddr) String()string

typeIPConn

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

IPConn is the implementation of theConn andPacketConn interfacesfor IP network connections.

funcDialIP

func DialIP(networkstring, laddr, raddr *IPAddr) (*IPConn,error)

DialIP acts likeDial 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, thelocal system is assumed.

funcListenIP

func ListenIP(networkstring, laddr *IPAddr) (*IPConn,error)

ListenIP acts likeListenPacket 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 systemexcept multicast IP addresses.

func (*IPConn)Close

func (c *IPConn) Close()error

Close closes the connection.

func (*IPConn)File

func (c *IPConn) File() (f *os.File, errerror)

File returns a copy of the underlyingos.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 duplicatemay 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, sodo 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 thePacketConn ReadFrom method.

func (*IPConn)ReadFromIP

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

ReadFromIP acts like ReadFrom but returns an IPAddr.

func (*IPConn)ReadMsgIPadded ingo1.1

func (c *IPConn) ReadMsgIP(b, oob []byte) (n, oobn, flagsint, addr *IPAddr, errerror)

ReadMsgIP reads a message from c, copying the payload into b andthe associated out-of-band data into oob. It returns the number ofbytes copied into b, the number of bytes copied into oob, the flagsthat 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 beused 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, sodo not modify it.

func (*IPConn)SetDeadline

func (c *IPConn) SetDeadline(ttime.Time)error

SetDeadline implements the Conn SetDeadline method.

func (*IPConn)SetReadBuffer

func (c *IPConn) SetReadBuffer(bytesint)error

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

func (*IPConn)SetReadDeadline

func (c *IPConn) SetReadDeadline(ttime.Time)error

SetReadDeadline implements the Conn SetReadDeadline method.

func (*IPConn)SetWriteBuffer

func (c *IPConn) SetWriteBuffer(bytesint)error

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

func (*IPConn)SetWriteDeadline

func (c *IPConn) SetWriteDeadline(ttime.Time)error

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*IPConn)SyscallConnadded ingo1.9

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

SyscallConn returns a raw network connection.This implements thesyscall.Conn interface.

func (*IPConn)Write

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

Write implements the Conn Write method.

func (*IPConn)WriteMsgIPadded ingo1.1

func (c *IPConn) WriteMsgIP(b, oob []byte, addr *IPAddr) (n, oobnint, errerror)

WriteMsgIP writes a message to addr via c, copying the payload fromb and the associated out-of-band data from oob. It returns thenumber of payload and out-of-band bytes written.

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

func (*IPConn)WriteTo

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

WriteTo implements thePacketConn WriteTo method.

func (*IPConn)WriteToIP

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

WriteToIP acts likeIPConn.WriteTo but takes anIPAddr.

typeIPMask

type IPMask []byte

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

See typeIPNet and funcParseCIDR for details.

funcCIDRMask

func CIDRMask(ones, bitsint)IPMask

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

Example
package mainimport ("fmt""net")func main() {// This mask corresponds to a /31 subnet for IPv4.fmt.Println(net.CIDRMask(31, 32))// This mask corresponds to a /64 subnet for IPv6.fmt.Println(net.CIDRMask(64, 128))}
Output:fffffffeffffffffffffffff0000000000000000

funcIPv4Mask

func IPv4Mask(a, b, c, dbyte)IPMask

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

Example
package mainimport ("fmt""net")func main() {fmt.Println(net.IPv4Mask(255, 255, 255, 0))}
Output:ffffff00

func (IPMask)Size

func (mIPMask) Size() (ones, bitsint)

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--thenSize returns 0, 0.

func (IPMask)String

func (mIPMask) String()string

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

typeIPNet

type IPNet struct {IPIP// network numberMaskIPMask// network mask}

An IPNet represents an IP network.

func (*IPNet)Contains

func (n *IPNet) Contains(ipIP)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 inRFC 4632 andRFC 4291.If the mask is not in the canonical form, it returns thestring which consists of an IP address, followed by a slashcharacter and a mask expressed as hexadecimal form with nopunctuation like "198.51.100.0/c000ff00".

typeInterface

type Interface struct {Indexint// positive integer that starts at one, zero is never usedMTUint// maximum transmission unitNamestring// e.g., "en0", "lo0", "eth0.100"HardwareAddrHardwareAddr// IEEE MAC-48, EUI-48 and EUI-64 formFlagsFlags// e.g., FlagUp, FlagLoopback, FlagMulticast}

Interface represents a mapping between network interface nameand index. It also represents network interface facilityinformation.

funcInterfaceByIndex

func InterfaceByIndex(indexint) (*Interface,error)

InterfaceByIndex returns the interface specified by index.

On Solaris, it returns one of the logical network interfacessharing the logical data link; for more precision useInterfaceByName.

funcInterfaceByName

func InterfaceByName(namestring) (*Interface,error)

InterfaceByName returns the interface specified by name.

funcInterfaces

func Interfaces() ([]Interface,error)

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

func (*Interface)Addrs

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

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

func (*Interface)MulticastAddrs

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

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

typeInvalidAddrError

type InvalidAddrErrorstring

func (InvalidAddrError)Error

func (eInvalidAddrError) Error()string

func (InvalidAddrError)Temporary

func (eInvalidAddrError) Temporary()bool

func (InvalidAddrError)Timeout

func (eInvalidAddrError) Timeout()bool

typeKeepAliveConfigadded ingo1.23.0

type KeepAliveConfig struct {// If Enable is true, keep-alive probes are enabled.Enablebool// Idle is the time that the connection must be idle before// the first keep-alive probe is sent.// If zero, a default value of 15 seconds is used.Idletime.Duration// Interval is the time between keep-alive probes.// If zero, a default value of 15 seconds is used.Intervaltime.Duration// Count is the maximum number of keep-alive probes that// can go unanswered before dropping a connection.// If zero, a default value of 9 is used.Countint}

KeepAliveConfig contains TCP keep-alive options.

If the Idle, Interval, or Count fields are zero, a default value is chosen.If a field is negative, the corresponding socket-level option will be left unchanged.

Note that prior to Windows 10 version 1709, neither setting Idle and Intervalseparately nor changing Count (which is usually 10) is supported.Therefore, it's recommended to set both Idle and Interval to non-negative valuesin conjunction with a -1 for Count on those old Windows if you intend to customizethe TCP keep-alive settings.By contrast, if only one of Idle and Interval is set to a non-negative value,the other will be set to the system default value, and ultimately,set both Idle and Interval to negative values if you want to leave them unchanged.

Note that Solaris and its derivatives do not support setting Interval to a non-negative valueand Count to a negative value, or vice-versa.

typeListenConfigadded ingo1.11

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 function are not// necessarily the ones passed to Listen. Calling Listen with TCP networks// will cause the Control function to be called with "tcp4" or "tcp6",// UDP networks become "udp4" or "udp6", IP networks become "ip4" or "ip6",// and other known networks are passed as-is.Control func(network, addressstring, csyscall.RawConn)error// KeepAlive specifies the keep-alive period for network// connections accepted by this listener.//// KeepAlive is ignored if KeepAliveConfig.Enable is true.//// If zero, keep-alive are enabled if supported by the protocol// and operating system. Network protocols or operating systems// that do not support keep-alive ignore this field.// If negative, keep-alive are disabled.KeepAlivetime.Duration// KeepAliveConfig specifies the keep-alive probe configuration// for an active network connection, when supported by the// protocol and operating system.//// If KeepAliveConfig.Enable is true, keep-alive probes are enabled.// If KeepAliveConfig.Enable is false and KeepAlive is negative,// keep-alive probes are disabled.KeepAliveConfigKeepAliveConfig// contains filtered or unexported fields}

ListenConfig contains options for listening to an address.

func (*ListenConfig)Listenadded ingo1.11

func (lc *ListenConfig) Listen(ctxcontext.Context, network, addressstring) (Listener,error)

Listen announces on the local network address.

See func Listen for a description of the network and addressparameters.

The ctx argument is used while resolving the address on which to listen;it does not affect the returned Listener.

func (*ListenConfig)ListenPacketadded ingo1.11

func (lc *ListenConfig) ListenPacket(ctxcontext.Context, network, addressstring) (PacketConn,error)

ListenPacket announces on the local network address.

See func ListenPacket for a description of the network and addressparameters.

The ctx argument is used while resolving the address on which to listen;it does not affect the returned Listener.

func (*ListenConfig)MultipathTCPadded ingo1.21.0

func (lc *ListenConfig) MultipathTCP()bool

MultipathTCP reports whether MPTCP will be used.

This method doesn't check if MPTCP is supported by the operatingsystem or not.

func (*ListenConfig)SetMultipathTCPadded ingo1.21.0

func (lc *ListenConfig) SetMultipathTCP(usebool)

SetMultipathTCP directs theListen method to use, or not use, MPTCP,if supported by the operating system. This method overrides thesystem default and the GODEBUG=multipathtcp=... setting if any.

If MPTCP is not available on the host or not supported by the client,the Listen method will fall back to TCP.

typeListener

type Listener interface {// Accept waits for and returns the next connection to the listener.Accept() (Conn,error)// Close closes the listener.// Any blocked Accept operations will be unblocked and return errors.Close()error// Addr returns the listener's network address.Addr()Addr}

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

Multiple goroutines may invoke methods on a Listener simultaneously.

Example
package mainimport ("io""log""net")func main() {// Listen on TCP port 2000 on all available unicast and// anycast IP addresses of the local system.l, err := net.Listen("tcp", ":2000")if err != nil {log.Fatal(err)}defer l.Close()for {// Wait for a connection.conn, err := l.Accept()if err != nil {log.Fatal(err)}// Handle the connection in a new goroutine.// The loop then returns to accepting, so that// multiple connections may be served concurrently.go func(c net.Conn) {// Echo all incoming data.io.Copy(c, c)// Shut down the connection.c.Close()}(conn)}}
Output:

funcFileListener

func FileListener(f *os.File) (lnListener, errerror)

FileListener returns a copy of the network listener correspondingto 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.

funcListen

func Listen(network, addressstring) (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 ora literal unspecified IP address, Listen listens on all availableunicast 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 IPaddresses.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.TheAddr method ofListener can be used to discover the chosenport.

See funcDial for a description of the network and addressparameters.

Listen uses context.Background internally; to specify the context, useListenConfig.Listen.

typeMX

type MX struct {HoststringPrefuint16}

An MX represents a single DNS MX record.

funcLookupMX

func LookupMX(namestring) ([]*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 properlyformatted presentation-format domain names. If the response containsinvalid names, those records are filtered out and an errorwill be returned alongside the remaining results, if any.

LookupMX usescontext.Background internally; to specify the context, useResolver.LookupMX.

typeNSadded ingo1.1

type NS struct {Hoststring}

An NS represents a single DNS NS record.

funcLookupNSadded ingo1.1

func LookupNS(namestring) ([]*NS,error)

LookupNS returns the DNS NS records for the given domain name.

The returned name server names are validated to be properlyformatted presentation-format domain names. If the response containsinvalid names, those records are filtered out and an errorwill be returned alongside the remaining results, if any.

LookupNS usescontext.Background internally; to specify the context, useResolver.LookupNS.

typeOpError

type OpError struct {// Op is the operation which caused the error, such as// "read" or "write".Opstring// Net is the network type on which this error occurred,// such as "tcp" or "udp6".Netstring// For operations involving a remote network connection, like// Dial, Read, or Write, Source is the corresponding local// network address.SourceAddr// 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.AddrAddr// Err is the error that occurred during the operation.// The Error method panics if the error is nil.Errerror}

OpError is the error type usually returned by functions in the netpackage. It describes the operation, network type, and address ofan 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)Unwrapadded ingo1.13

func (e *OpError) Unwrap()error

typePacketConn

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

PacketConn is a generic packet-oriented network connection.

Multiple goroutines may invoke methods on a PacketConn simultaneously.

funcFilePacketConn

func FilePacketConn(f *os.File) (cPacketConn, errerror)

FilePacketConn returns a copy of the packet network connectioncorresponding 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.

funcListenPacket

func ListenPacket(network, addressstring) (PacketConn,error)

ListenPacket announces on the local network address.

The network must be "udp", "udp4", "udp6", "unixgram", or an IPtransport. The IP transports are "ip", "ip4", or "ip6" followed bya 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 isempty or a literal unspecified IP address, ListenPacket listens onall available IP addresses of the local system except multicast IPaddresses.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 IPaddresses.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 ofPacketConn can be used to discover thechosen port.

See funcDial for a description of the network and addressparameters.

ListenPacket uses context.Background internally; to specify the context, useListenConfig.ListenPacket.

typeParseError

type ParseError struct {// Type is the type of string that was expected, such as// "IP address", "CIDR address".Typestring// Text is the malformed text string.Textstring}

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

func (*ParseError)Error

func (e *ParseError) Error()string

func (*ParseError)Temporaryadded ingo1.17

func (e *ParseError) Temporary()bool

func (*ParseError)Timeoutadded ingo1.17

func (e *ParseError) Timeout()bool

typeResolveradded ingo1.8

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.PreferGobool// 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.StrictErrorsbool// 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 toRFC 1035 section 4.2.1, "UDP usage".// Otherwise, DNS messages transmitted over Conn must adhere// toRFC 7766 section 5, "Transport Protocol Selection".// If nil, the default dialer is used.Dial func(ctxcontext.Context, network, addressstring) (Conn,error)// contains filtered or unexported fields}

A Resolver looks up names and numbers.

A nil *Resolver is equivalent to a zero Resolver.

func (*Resolver)LookupAddradded ingo1.8

func (r *Resolver) LookupAddr(ctxcontext.Context, addrstring) ([]string,error)

LookupAddr performs a reverse lookup for the given address, returning a listof names mapping to that address.

The returned names are validated to be properly formatted presentation-formatdomain names. If the response contains invalid names, those records are filteredout and an error will be returned alongside the remaining results, if any.

func (*Resolver)LookupCNAMEadded ingo1.8

func (r *Resolver) LookupCNAME(ctxcontext.Context, hoststring) (string,error)

LookupCNAME returns the canonical name for the given host.Callers that do not care about the canonical name can callLookupHost orLookupIP directly; both take care of resolvingthe canonical name as part of the lookup.

A canonical name is the final name after following zeroor more CNAME records.LookupCNAME does not return an error if host does notcontain DNS "CNAME" records, as long as host resolves toaddress records.

The returned canonical name is validated to be a properlyformatted presentation-format domain name.

func (*Resolver)LookupHostadded ingo1.8

func (r *Resolver) LookupHost(ctxcontext.Context, hoststring) (addrs []string, errerror)

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

func (*Resolver)LookupIPadded ingo1.15

func (r *Resolver) LookupIP(ctxcontext.Context, network, hoststring) ([]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 bynetwork.network must be one of "ip", "ip4" or "ip6".

func (*Resolver)LookupIPAddradded ingo1.8

func (r *Resolver) LookupIPAddr(ctxcontext.Context, hoststring) ([]IPAddr,error)

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

func (*Resolver)LookupMXadded ingo1.8

func (r *Resolver) LookupMX(ctxcontext.Context, namestring) ([]*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 properlyformatted presentation-format domain names. If the response containsinvalid names, those records are filtered out and an errorwill be returned alongside the remaining results, if any.

func (*Resolver)LookupNSadded ingo1.8

func (r *Resolver) LookupNS(ctxcontext.Context, namestring) ([]*NS,error)

LookupNS returns the DNS NS records for the given domain name.

The returned name server names are validated to be properlyformatted presentation-format domain names. If the response containsinvalid names, those records are filtered out and an errorwill be returned alongside the remaining results, if any.

func (*Resolver)LookupNetIPadded ingo1.18

func (r *Resolver) LookupNetIP(ctxcontext.Context, network, hoststring) ([]netip.Addr,error)

LookupNetIP looks up host using the local resolver.It returns a slice of that host's IP addresses of the type specified bynetwork.The network must be one of "ip", "ip4" or "ip6".

func (*Resolver)LookupPortadded ingo1.8

func (r *Resolver) LookupPort(ctxcontext.Context, network, servicestring) (portint, errerror)

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

The network must be one of "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6" or "ip".

func (*Resolver)LookupSRVadded ingo1.8

func (r *Resolver) LookupSRV(ctxcontext.Context, service, proto, namestring) (string, []*SRV,error)

LookupSRV tries to resolve anSRV query of the given service,protocol, and domain name. The proto is "tcp" or "udp".The returned records are sorted by priority and randomizedby weight within a priority.

LookupSRV constructs the DNS name to look up followingRFC 2782.That is, it looks up _service._proto.name. To accommodate servicespublishing SRV records under non-standard names, if both serviceand proto are empty strings, LookupSRV looks up name directly.

The returned service names are validated to be properlyformatted presentation-format domain names. If the response containsinvalid names, those records are filtered out and an errorwill be returned alongside the remaining results, if any.

func (*Resolver)LookupTXTadded ingo1.8

func (r *Resolver) LookupTXT(ctxcontext.Context, namestring) ([]string,error)

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

If a DNS TXT record holds multiple strings, they are concatenated as asingle string.

typeSRV

type SRV struct {TargetstringPortuint16Priorityuint16Weightuint16}

An SRV represents a single DNS SRV record.

funcLookupSRV

func LookupSRV(service, proto, namestring) (cnamestring, addrs []*SRV, errerror)

LookupSRV tries to resolve anSRV query of the given service,protocol, and domain name. The proto is "tcp" or "udp".The returned records are sorted by priority and randomizedby weight within a priority.

LookupSRV constructs the DNS name to look up followingRFC 2782.That is, it looks up _service._proto.name. To accommodate servicespublishing SRV records under non-standard names, if both serviceand proto are empty strings, LookupSRV looks up name directly.

The returned service names are validated to be properlyformatted presentation-format domain names. If the response containsinvalid names, those records are filtered out and an errorwill be returned alongside the remaining results, if any.

typeTCPAddr

type TCPAddr struct {IPIPPortintZonestring// IPv6 scoped addressing zone}

TCPAddr represents the address of a TCP end point.

funcResolveTCPAddr

func ResolveTCPAddr(network, addressstring) (*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 orthe port is not a literal port number, ResolveTCPAddr resolves theaddress to an address of TCP end point.Otherwise, it parses the address as a pair of literal IP addressand port number.The address parameter can use a host name, but this is notrecommended, because it will return at most one of the host name'sIP addresses.

See funcDial for a description of the network and addressparameters.

funcTCPAddrFromAddrPortadded ingo1.18

func TCPAddrFromAddrPort(addrnetip.AddrPort) *TCPAddr

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

func (*TCPAddr)AddrPortadded ingo1.18

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

AddrPort returns theTCPAddr a as anetip.AddrPort.

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

If a is nil, a zero value is returned.

func (*TCPAddr)Network

func (a *TCPAddr) Network()string

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

func (*TCPAddr)String

func (a *TCPAddr) String()string

typeTCPConn

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

TCPConn is an implementation of theConn interface for TCP networkconnections.

funcDialTCP

func DialTCP(networkstring, laddr, raddr *TCPAddr) (*TCPConn,error)

DialTCP acts likeDial 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, thelocal system is assumed.

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, errerror)

File returns a copy of the underlyingos.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 duplicatemay 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, sodo not modify it.

func (*TCPConn)MultipathTCPadded ingo1.21.0

func (c *TCPConn) MultipathTCP() (bool,error)

MultipathTCP reports whether the ongoing connection is using MPTCP.

If Multipath TCP is not supported by the host, by the other peer orintentionally / accidentally filtered out by a device in between, afallback to TCP will be done. This method does its best to check ifMPTCP is still being used or not.

On Linux, more conditions are verified on kernels >= v5.16, improvingthe results.

func (*TCPConn)Read

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

Read implements the Conn Read method.

func (*TCPConn)ReadFrom

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

ReadFrom implements theio.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, sodo not modify it.

func (*TCPConn)SetDeadline

func (c *TCPConn) SetDeadline(ttime.Time)error

SetDeadline implements the Conn SetDeadline method.

func (*TCPConn)SetKeepAlive

func (c *TCPConn) SetKeepAlive(keepalivebool)error

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

func (*TCPConn)SetKeepAliveConfigadded ingo1.23.0

func (c *TCPConn) SetKeepAliveConfig(configKeepAliveConfig)error

SetKeepAliveConfig configures keep-alive messages sent by the operating system.

func (*TCPConn)SetKeepAlivePeriodadded ingo1.2

func (c *TCPConn) SetKeepAlivePeriod(dtime.Duration)error

SetKeepAlivePeriod sets the duration the connection needs toremain idle before TCP starts sending keepalive probes.

Note that calling this method on Windows prior to Windows 10 version 1709will reset the KeepAliveInterval to the default system value, which is normally 1 second.

func (*TCPConn)SetLinger

func (c *TCPConn) SetLinger(secint)error

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

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

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

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

func (*TCPConn)SetNoDelay

func (c *TCPConn) SetNoDelay(noDelaybool)error

SetNoDelay controls whether the operating system should delaypacket transmission in hopes of sending fewer packets (Nagle'salgorithm). The default is true (no delay), meaning that data issent as soon as possible after a Write.

func (*TCPConn)SetReadBuffer

func (c *TCPConn) SetReadBuffer(bytesint)error

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

func (*TCPConn)SetReadDeadline

func (c *TCPConn) SetReadDeadline(ttime.Time)error

SetReadDeadline implements the Conn SetReadDeadline method.

func (*TCPConn)SetWriteBuffer

func (c *TCPConn) SetWriteBuffer(bytesint)error

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

func (*TCPConn)SetWriteDeadline

func (c *TCPConn) SetWriteDeadline(ttime.Time)error

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*TCPConn)SyscallConnadded ingo1.9

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

SyscallConn returns a raw network connection.This implements thesyscall.Conn interface.

func (*TCPConn)Write

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

Write implements the Conn Write method.

func (*TCPConn)WriteToadded ingo1.22.0

func (c *TCPConn) WriteTo(wio.Writer) (int64,error)

WriteTo implements the io.WriterTo WriteTo method.

typeTCPListener

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

TCPListener is a TCP network listener. Clients should typicallyuse variables of typeListener instead of assuming TCP.

funcListenTCP

func ListenTCP(networkstring, laddr *TCPAddr) (*TCPListener,error)

ListenTCP acts likeListen 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 addressesof the local system.If the Port field of laddr is 0, a port number is automaticallychosen.

func (*TCPListener)Accept

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

Accept implements the Accept method in theListener interface; itwaits for the next call and returns a genericConn.

func (*TCPListener)AcceptTCP

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

AcceptTCP accepts the next incoming call and returns the newconnection.

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, sodo 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, errerror)

File returns a copy of the underlyingos.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 theconnection's. Attempting to change properties of the originalusing this duplicate may or may not have the desired effect.

func (*TCPListener)SetDeadline

func (l *TCPListener) SetDeadline(ttime.Time)error

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

func (*TCPListener)SyscallConnadded ingo1.10

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

SyscallConn returns a raw network connection.This implements thesyscall.Conn interface.

The returned RawConn only supports calling Control. Read andWrite return an error.

typeUDPAddr

type UDPAddr struct {IPIPPortintZonestring// IPv6 scoped addressing zone}

UDPAddr represents the address of a UDP end point.

funcResolveUDPAddr

func ResolveUDPAddr(network, addressstring) (*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 orthe port is not a literal port number, ResolveUDPAddr resolves theaddress to an address of UDP end point.Otherwise, it parses the address as a pair of literal IP addressand port number.The address parameter can use a host name, but this is notrecommended, because it will return at most one of the host name'sIP addresses.

See funcDial for a description of the network and addressparameters.

funcUDPAddrFromAddrPortadded ingo1.18

func UDPAddrFromAddrPort(addrnetip.AddrPort) *UDPAddr

UDPAddrFromAddrPort returns addr as aUDPAddr. If addr.IsValid() is false,then the returned UDPAddr will contain a nil IP field, indicating anaddress family-agnostic unspecified address.

func (*UDPAddr)AddrPortadded ingo1.18

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

AddrPort returns theUDPAddr a as anetip.AddrPort.

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

If a is nil, a zero value is returned.

func (*UDPAddr)Network

func (a *UDPAddr) Network()string

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

func (*UDPAddr)String

func (a *UDPAddr) String()string

typeUDPConn

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

UDPConn is the implementation of theConn andPacketConn interfacesfor UDP network connections.

funcDialUDP

func DialUDP(networkstring, laddr, raddr *UDPAddr) (*UDPConn,error)

DialUDP acts likeDial for UDP networks.

The network must be a UDP network name; see funcDial 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, thelocal system is assumed.

funcListenMulticastUDP

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

ListenMulticastUDP acts likeListenPacket for UDP networks buttakes a group address on a specific network interface.

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

ListenMulticastUDP listens on all available IP addresses of thelocal system including the group, multicast IP address.If ifi is nil, ListenMulticastUDP uses the system-assignedmulticast interface, although this is not recommended because theassignment depends on platforms and sometimes it might requirerouting configuration.If the Port field of gaddr is 0, a port number is automaticallychosen.

ListenMulticastUDP is just for convenience of simple, smallapplications. There aregolang.org/x/net/ipv4 andgolang.org/x/net/ipv6 packages for general purpose uses.

Note that ListenMulticastUDP will set the IP_MULTICAST_LOOP socket optionto 0 under IPPROTO_IP, to disable loopback of multicast packets.

funcListenUDP

func ListenUDP(networkstring, laddr *UDPAddr) (*UDPConn,error)

ListenUDP acts likeListenPacket for UDP networks.

The network must be a UDP network name; see funcDial 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 systemexcept multicast IP addresses.If the Port field of laddr is 0, a port number is automaticallychosen.

func (*UDPConn)Close

func (c *UDPConn) Close()error

Close closes the connection.

func (*UDPConn)File

func (c *UDPConn) File() (f *os.File, errerror)

File returns a copy of the underlyingos.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 duplicatemay 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, sodo 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 thePacketConn ReadFrom method.

func (*UDPConn)ReadFromUDP

func (c *UDPConn) ReadFromUDP(b []byte) (nint, addr *UDPAddr, errerror)

ReadFromUDP acts likeUDPConn.ReadFrom but returns a UDPAddr.

func (*UDPConn)ReadFromUDPAddrPortadded ingo1.18

func (c *UDPConn) ReadFromUDPAddrPort(b []byte) (nint, addrnetip.AddrPort, errerror)

ReadFromUDPAddrPort acts like ReadFrom but returns anetip.AddrPort.

If c is bound to an unspecified address, the returnednetip.AddrPort's address might be an IPv4-mapped IPv6 address.Usenetip.Addr.Unmap to get the address without the IPv6 prefix.

func (*UDPConn)ReadMsgUDPadded ingo1.1

func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flagsint, addr *UDPAddr, errerror)

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

The packagesgolang.org/x/net/ipv4 andgolang.org/x/net/ipv6 can beused to manipulate IP-level socket options in oob.

func (*UDPConn)ReadMsgUDPAddrPortadded ingo1.18

func (c *UDPConn) ReadMsgUDPAddrPort(b, oob []byte) (n, oobn, flagsint, addrnetip.AddrPort, errerror)

ReadMsgUDPAddrPort is likeUDPConn.ReadMsgUDP but returns annetip.AddrPort instead of aUDPAddr.

func (*UDPConn)RemoteAddr

func (c *UDPConn) RemoteAddr()Addr

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

func (*UDPConn)SetDeadline

func (c *UDPConn) SetDeadline(ttime.Time)error

SetDeadline implements the Conn SetDeadline method.

func (*UDPConn)SetReadBuffer

func (c *UDPConn) SetReadBuffer(bytesint)error

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

func (*UDPConn)SetReadDeadline

func (c *UDPConn) SetReadDeadline(ttime.Time)error

SetReadDeadline implements the Conn SetReadDeadline method.

func (*UDPConn)SetWriteBuffer

func (c *UDPConn) SetWriteBuffer(bytesint)error

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

func (*UDPConn)SetWriteDeadline

func (c *UDPConn) SetWriteDeadline(ttime.Time)error

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*UDPConn)SyscallConnadded ingo1.9

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

SyscallConn returns a raw network connection.This implements thesyscall.Conn interface.

func (*UDPConn)Write

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

Write implements the Conn Write method.

func (*UDPConn)WriteMsgUDPadded ingo1.1

func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobnint, errerror)

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

The packagesgolang.org/x/net/ipv4 andgolang.org/x/net/ipv6 can beused to manipulate IP-level socket options in oob.

func (*UDPConn)WriteMsgUDPAddrPortadded ingo1.18

func (c *UDPConn) WriteMsgUDPAddrPort(b, oob []byte, addrnetip.AddrPort) (n, oobnint, errerror)

WriteMsgUDPAddrPort is likeUDPConn.WriteMsgUDP but takes anetip.AddrPort instead of aUDPAddr.

func (*UDPConn)WriteTo

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

WriteTo implements thePacketConn WriteTo method.

Example
package mainimport ("log""net")func main() {// Unlike Dial, ListenPacket creates a connection without any// association with peers.conn, err := net.ListenPacket("udp", ":0")if err != nil {log.Fatal(err)}defer conn.Close()dst, err := net.ResolveUDPAddr("udp", "192.0.2.1:2000")if err != nil {log.Fatal(err)}// The connection can write data to the desired address._, err = conn.WriteTo([]byte("data"), dst)if err != nil {log.Fatal(err)}}
Output:

func (*UDPConn)WriteToUDP

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

WriteToUDP acts likeUDPConn.WriteTo but takes aUDPAddr.

func (*UDPConn)WriteToUDPAddrPortadded ingo1.18

func (c *UDPConn) WriteToUDPAddrPort(b []byte, addrnetip.AddrPort) (int,error)

WriteToUDPAddrPort acts likeUDPConn.WriteTo but takes anetip.AddrPort.

typeUnixAddr

type UnixAddr struct {NamestringNetstring}

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

funcResolveUnixAddr

func ResolveUnixAddr(network, addressstring) (*UnixAddr,error)

ResolveUnixAddr returns an address of Unix domain socket end point.

The network must be a Unix network name.

See funcDial for a description of the network and addressparameters.

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

typeUnixConn

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

UnixConn is an implementation of theConn interface for connectionsto Unix domain sockets.

funcDialUnix

func DialUnix(networkstring, laddr, raddr *UnixAddr) (*UnixConn,error)

DialUnix acts likeDial 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 theconnection.

funcListenUnixgram

func ListenUnixgram(networkstring, laddr *UnixAddr) (*UnixConn,error)

ListenUnixgram acts likeListenPacket for Unix networks.

The network must be "unixgram".

func (*UnixConn)Close

func (c *UnixConn) Close()error

Close closes the connection.

func (*UnixConn)CloseReadadded ingo1.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)CloseWriteadded ingo1.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, errerror)

File returns a copy of the underlyingos.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 duplicatemay 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, sodo 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 thePacketConn ReadFrom method.

func (*UnixConn)ReadFromUnix

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

ReadFromUnix acts likeUnixConn.ReadFrom but returns aUnixAddr.

func (*UnixConn)ReadMsgUnix

func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flagsint, addr *UnixAddr, errerror)

ReadMsgUnix reads a message from c, copying the payload into b andthe associated out-of-band data into oob. It returns the number ofbytes copied into b, the number of bytes copied into oob, the flagsthat 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 stillread (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, sodo not modify it.

func (*UnixConn)SetDeadline

func (c *UnixConn) SetDeadline(ttime.Time)error

SetDeadline implements the Conn SetDeadline method.

func (*UnixConn)SetReadBuffer

func (c *UnixConn) SetReadBuffer(bytesint)error

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

func (*UnixConn)SetReadDeadline

func (c *UnixConn) SetReadDeadline(ttime.Time)error

SetReadDeadline implements the Conn SetReadDeadline method.

func (*UnixConn)SetWriteBuffer

func (c *UnixConn) SetWriteBuffer(bytesint)error

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

func (*UnixConn)SetWriteDeadline

func (c *UnixConn) SetWriteDeadline(ttime.Time)error

SetWriteDeadline implements the Conn SetWriteDeadline method.

func (*UnixConn)SyscallConnadded ingo1.9

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

SyscallConn returns a raw network connection.This implements thesyscall.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, oobnint, errerror)

WriteMsgUnix writes a message to addr via c, copying the payloadfrom b and the associated out-of-band data from oob. It returns thenumber of payload and out-of-band bytes written.

Note that if len(b) == 0 and len(oob) > 0, this function will stillwrite 1 byte to the connection.

func (*UnixConn)WriteTo

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

WriteTo implements thePacketConn WriteTo method.

func (*UnixConn)WriteToUnix

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

WriteToUnix acts likeUnixConn.WriteTo but takes aUnixAddr.

typeUnixListener

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

UnixListener is a Unix domain socket listener. Clients shouldtypically use variables of typeListener instead of assuming Unixdomain sockets.

funcListenUnix

func ListenUnix(networkstring, laddr *UnixAddr) (*UnixListener,error)

ListenUnix acts likeListen for Unix networks.

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

func (*UnixListener)Accept

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

Accept implements the Accept method in theListener 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 newconnection.

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, sodo not modify it.

func (*UnixListener)Close

func (l *UnixListener) Close()error

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

func (*UnixListener)File

func (l *UnixListener) File() (f *os.File, errerror)

File returns a copy of the underlyingos.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 theconnection's. Attempting to change properties of the originalusing this duplicate may or may not have the desired effect.

func (*UnixListener)SetDeadline

func (l *UnixListener) SetDeadline(ttime.Time)error

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

func (*UnixListener)SetUnlinkOnCloseadded ingo1.8

func (l *UnixListener) SetUnlinkOnClose(unlinkbool)

SetUnlinkOnClose sets whether the underlying socket file should be removedfrom 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 toListen 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 existingsocket file, then by default closing the listener will not remove the socket file.

func (*UnixListener)SyscallConnadded ingo1.10

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

SyscallConn returns a raw network connection.This implements thesyscall.Conn interface.

The returned RawConn only supports calling Control. Read andWrite return an error.

typeUnknownNetworkError

type UnknownNetworkErrorstring

func (UnknownNetworkError)Error

func (UnknownNetworkError)Temporary

func (eUnknownNetworkError) Temporary()bool

func (UnknownNetworkError)Timeout

func (eUnknownNetworkError) Timeout()bool

Notes

Bugs

  • On JS and Windows, the FileConn, FileListener andFilePacketConn functions are not implemented.

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

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

  • On every POSIX platform, reads from the "ip4" networkusing the ReadFrom or ReadFromIP method might not return a completeIPv4 packet, including its header, even if there is spaceavailable. This can occur even in cases where Read or ReadMsgIPcould return a complete packet. For this reason, it is recommendedthat you do not use these methods if it is important to receive afull packet.

    The Go 1 compatibility guidelines make it impossible for us tochange the behavior of these methods; use Read or ReadMsgIPinstead.

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

  • On Windows, the File method of IPConn is notimplemented.

  • On DragonFly BSD and OpenBSD, listening on the"tcp" and "udp" networks does not listen for both IPv4 and IPv6connections. This is due to the fact that IPv4 traffic will not berouted to an IPv6 socket - two separate sockets are required ifboth address families are to be supported.See inet6(4) for details.

  • On Windows, the Write method of syscall.RawConndoes not integrate with the runtime's network poller. It cannotwait for the connection to become writeable, and does not respectdeadlines. If the user-provided callback returns false, the Writemethod will fail immediately.

  • On JS and Plan 9, the Control, Read and Writemethods of syscall.RawConn are not implemented.

  • On JS and Windows, the File method of TCPConn andTCPListener is not implemented.

  • On Plan 9, the ReadMsgUDP andWriteMsgUDP methods of UDPConn are not implemented.

  • On Windows, the File method of UDPConn is notimplemented.

  • On JS, methods and functions related to UDPConn are notimplemented.

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

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

Source Files

View all Source files

Directories

PathSynopsis
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations.
cgi
Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
cookiejar
Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
fcgi
Package fcgi implements the FastCGI protocol.
Package fcgi implements the FastCGI protocol.
httptest
Package httptest provides utilities for HTTP testing.
Package httptest provides utilities for HTTP testing.
httptrace
Package httptrace provides mechanisms to trace the events within HTTP client requests.
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.
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.
Package internal contains HTTP internals shared by net/http and net/http/httputil.
internal/testcert
Package testcert contains a test-only localhost certificate.
Package testcert contains a test-only localhost certificate.
pprof
Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
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.
Package socktest provides utilities for socket testing.
Package mail implements parsing of mail messages.
Package mail implements parsing of mail messages.
Package netip defines an IP address type that's a small value type.
Package netip defines an IP address type that's a small value type.
Package rpc provides access to the exported methods of an object across a network or other I/O connection.
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.
Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package.
Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
Package textproto implements generic support for text-based request/response protocols in the style of HTTP, NNTP, and SMTP.
Package textproto implements generic support for text-based request/response protocols in the style of HTTP, NNTP, and SMTP.
Package url parses URLs and implements query escaping.
Package url parses URLs and implements query escaping.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp