Source file src/net/dial.go

Documentation: net

     1  // Copyright 2010 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package net
     6  
     7  import (
     8  	"context"
     9  	"internal/nettrace"
    10  	"internal/poll"
    11  	"syscall"
    12  	"time"
    13  )
    14  
    15  // defaultTCPKeepAlive is a default constant value for TCPKeepAlive times
    16  // See golang.org/issue/31510
    17  const (
    18  	defaultTCPKeepAlive = 15 * time.Second
    19  )
    20  
    21  // A Dialer contains options for connecting to an address.
    22  //
    23  // The zero value for each field is equivalent to dialing
    24  // without that option. Dialing with the zero value of Dialer
    25  // is therefore equivalent to just calling the Dial function.
    26  //
    27  // It is safe to call Dialer's methods concurrently.
    28  type Dialer struct {
    29  	// Timeout is the maximum amount of time a dial will wait for
    30  	// a connect to complete. If Deadline is also set, it may fail
    31  	// earlier.
    32  	//
    33  	// The default is no timeout.
    34  	//
    35  	// When using TCP and dialing a host name with multiple IP
    36  	// addresses, the timeout may be divided between them.
    37  	//
    38  	// With or without a timeout, the operating system may impose
    39  	// its own earlier timeout. For instance, TCP timeouts are
    40  	// often around 3 minutes.
    41  	Timeout time.Duration
    42  
    43  	// Deadline is the absolute point in time after which dials
    44  	// will fail. If Timeout is set, it may fail earlier.
    45  	// Zero means no deadline, or dependent on the operating system
    46  	// as with the Timeout option.
    47  	Deadline time.Time
    48  
    49  	// LocalAddr is the local address to use when dialing an
    50  	// address. The address must be of a compatible type for the
    51  	// network being dialed.
    52  	// If nil, a local address is automatically chosen.
    53  	LocalAddr Addr
    54  
    55  	// DualStack previously enabled RFC 6555 Fast Fallback
    56  	// support, also known as "Happy Eyeballs", in which IPv4 is
    57  	// tried soon if IPv6 appears to be misconfigured and
    58  	// hanging.
    59  	//
    60  	// Deprecated: Fast Fallback is enabled by default. To
    61  	// disable, set FallbackDelay to a negative value.
    62  	DualStack bool
    63  
    64  	// FallbackDelay specifies the length of time to wait before
    65  	// spawning a RFC 6555 Fast Fallback connection. That is, this
    66  	// is the amount of time to wait for IPv6 to succeed before
    67  	// assuming that IPv6 is misconfigured and falling back to
    68  	// IPv4.
    69  	//
    70  	// If zero, a default delay of 300ms is used.
    71  	// A negative value disables Fast Fallback support.
    72  	FallbackDelay time.Duration
    73  
    74  	// KeepAlive specifies the interval between keep-alive
    75  	// probes for an active network connection.
    76  	// If zero, keep-alive probes are sent with a default value
    77  	// (currently 15 seconds), if supported by the protocol and operating
    78  	// system. Network protocols or operating systems that do
    79  	// not support keep-alives ignore this field.
    80  	// If negative, keep-alive probes are disabled.
    81  	KeepAlive time.Duration
    82  
    83  	// Resolver optionally specifies an alternate resolver to use.
    84  	Resolver *Resolver
    85  
    86  	// Cancel is an optional channel whose closure indicates that
    87  	// the dial should be canceled. Not all types of dials support
    88  	// cancellation.
    89  	//
    90  	// Deprecated: Use DialContext instead.
    91  	Cancel <-chan struct{}
    92  
    93  	// If Control is not nil, it is called after creating the network
    94  	// connection but before actually dialing.
    95  	//
    96  	// Network and address parameters passed to Control method are not
    97  	// necessarily the ones passed to Dial. For example, passing "tcp" to Dial
    98  	// will cause the Control function to be called with "tcp4" or "tcp6".
    99  	Control func(network, address string, c syscall.RawConn) error
   100  }
   101  
   102  func (d *Dialer) dualStack() bool { return d.FallbackDelay >= 0 }
   103  
   104  func minNonzeroTime(a, b time.Time) time.Time {
   105  	if a.IsZero() {
   106  		return b
   107  	}
   108  	if b.IsZero() || a.Before(b) {
   109  		return a
   110  	}
   111  	return b
   112  }
   113  
   114  // deadline returns the earliest of:
   115  //   - now+Timeout
   116  //   - d.Deadline
   117  //   - the context's deadline
   118  // Or zero, if none of Timeout, Deadline, or context's deadline is set.
   119  func (d *Dialer) deadline(ctx context.Context, now time.Time) (earliest time.Time) {
   120  	if d.Timeout != 0 { // including negative, for historical reasons
   121  		earliest = now.Add(d.Timeout)
   122  	}
   123  	if d, ok := ctx.Deadline(); ok {
   124  		earliest = minNonzeroTime(earliest, d)
   125  	}
   126  	return minNonzeroTime(earliest, d.Deadline)
   127  }
   128  
   129  func (d *Dialer) resolver() *Resolver {
   130  	if d.Resolver != nil {
   131  		return d.Resolver
   132  	}
   133  	return DefaultResolver
   134  }
   135  
   136  // partialDeadline returns the deadline to use for a single address,
   137  // when multiple addresses are pending.
   138  func partialDeadline(now, deadline time.Time, addrsRemaining int) (time.Time, error) {
   139  	if deadline.IsZero() {
   140  		return deadline, nil
   141  	}
   142  	timeRemaining := deadline.Sub(now)
   143  	if timeRemaining <= 0 {
   144  		return time.Time{}, poll.ErrTimeout
   145  	}
   146  	// Tentatively allocate equal time to each remaining address.
   147  	timeout := timeRemaining / time.Duration(addrsRemaining)
   148  	// If the time per address is too short, steal from the end of the list.
   149  	const saneMinimum = 2 * time.Second
   150  	if timeout < saneMinimum {
   151  		if timeRemaining < saneMinimum {
   152  			timeout = timeRemaining
   153  		} else {
   154  			timeout = saneMinimum
   155  		}
   156  	}
   157  	return now.Add(timeout), nil
   158  }
   159  
   160  func (d *Dialer) fallbackDelay() time.Duration {
   161  	if d.FallbackDelay > 0 {
   162  		return d.FallbackDelay
   163  	} else {
   164  		return 300 * time.Millisecond
   165  	}
   166  }
   167  
   168  func parseNetwork(ctx context.Context, network string, needsProto bool) (afnet string, proto int, err error) {
   169  	i := last(network, ':')
   170  	if i < 0 { // no colon
   171  		switch network {
   172  		case "tcp", "tcp4", "tcp6":
   173  		case "udp", "udp4", "udp6":
   174  		case "ip", "ip4", "ip6":
   175  			if needsProto {
   176  				return "", 0, UnknownNetworkError(network)
   177  			}
   178  		case "unix", "unixgram", "unixpacket":
   179  		default:
   180  			return "", 0, UnknownNetworkError(network)
   181  		}
   182  		return network, 0, nil
   183  	}
   184  	afnet = network[:i]
   185  	switch afnet {
   186  	case "ip", "ip4", "ip6":
   187  		protostr := network[i+1:]
   188  		proto, i, ok := dtoi(protostr)
   189  		if !ok || i != len(protostr) {
   190  			proto, err = lookupProtocol(ctx, protostr)
   191  			if err != nil {
   192  				return "", 0, err
   193  			}
   194  		}
   195  		return afnet, proto, nil
   196  	}
   197  	return "", 0, UnknownNetworkError(network)
   198  }
   199  
   200  // resolveAddrList resolves addr using hint and returns a list of
   201  // addresses. The result contains at least one address when error is
   202  // nil.
   203  func (r *Resolver) resolveAddrList(ctx context.Context, op, network, addr string, hint Addr) (addrList, error) {
   204  	afnet, _, err := parseNetwork(ctx, network, true)
   205  	if err != nil {
   206  		return nil, err
   207  	}
   208  	if op == "dial" && addr == "" {
   209  		return nil, errMissingAddress
   210  	}
   211  	switch afnet {
   212  	case "unix", "unixgram", "unixpacket":
   213  		addr, err := ResolveUnixAddr(afnet, addr)
   214  		if err != nil {
   215  			return nil, err
   216  		}
   217  		if op == "dial" && hint != nil && addr.Network() != hint.Network() {
   218  			return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()}
   219  		}
   220  		return addrList{addr}, nil
   221  	}
   222  	addrs, err := r.internetAddrList(ctx, afnet, addr)
   223  	if err != nil || op != "dial" || hint == nil {
   224  		return addrs, err
   225  	}
   226  	var (
   227  		tcp      *TCPAddr
   228  		udp      *UDPAddr
   229  		ip       *IPAddr
   230  		wildcard bool
   231  	)
   232  	switch hint := hint.(type) {
   233  	case *TCPAddr:
   234  		tcp = hint
   235  		wildcard = tcp.isWildcard()
   236  	case *UDPAddr:
   237  		udp = hint
   238  		wildcard = udp.isWildcard()
   239  	case *IPAddr:
   240  		ip = hint
   241  		wildcard = ip.isWildcard()
   242  	}
   243  	naddrs := addrs[:0]
   244  	for _, addr := range addrs {
   245  		if addr.Network() != hint.Network() {
   246  			return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()}
   247  		}
   248  		switch addr := addr.(type) {
   249  		case *TCPAddr:
   250  			if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(tcp.IP) {
   251  				continue
   252  			}
   253  			naddrs = append(naddrs, addr)
   254  		case *UDPAddr:
   255  			if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(udp.IP) {
   256  				continue
   257  			}
   258  			naddrs = append(naddrs, addr)
   259  		case *IPAddr:
   260  			if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(ip.IP) {
   261  				continue
   262  			}
   263  			naddrs = append(naddrs, addr)
   264  		}
   265  	}
   266  	if len(naddrs) == 0 {
   267  		return nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: hint.String()}
   268  	}
   269  	return naddrs, nil
   270  }
   271  
   272  // Dial connects to the address on the named network.
   273  //
   274  // Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only),
   275  // "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4"
   276  // (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and
   277  // "unixpacket".
   278  //
   279  // For TCP and UDP networks, the address has the form "host:port".
   280  // The host must be a literal IP address, or a host name that can be
   281  // resolved to IP addresses.
   282  // The port must be a literal port number or a service name.
   283  // If the host is a literal IPv6 address it must be enclosed in square
   284  // brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80".
   285  // The zone specifies the scope of the literal IPv6 address as defined
   286  // in RFC 4007.
   287  // The functions JoinHostPort and SplitHostPort manipulate a pair of
   288  // host and port in this form.
   289  // When using TCP, and the host resolves to multiple IP addresses,
   290  // Dial will try each IP address in order until one succeeds.
   291  //
   292  // Examples:
   293  //	Dial("tcp", "golang.org:http")
   294  //	Dial("tcp", "192.0.2.1:http")
   295  //	Dial("tcp", "198.51.100.1:80")
   296  //	Dial("udp", "[2001:db8::1]:domain")
   297  //	Dial("udp", "[fe80::1%lo0]:53")
   298  //	Dial("tcp", ":80")
   299  //
   300  // For IP networks, the network must be "ip", "ip4" or "ip6" followed
   301  // by a colon and a literal protocol number or a protocol name, and
   302  // the address has the form "host". The host must be a literal IP
   303  // address or a literal IPv6 address with zone.
   304  // It depends on each operating system how the operating system
   305  // behaves with a non-well known protocol number such as "0" or "255".
   306  //
   307  // Examples:
   308  //	Dial("ip4:1", "192.0.2.1")
   309  //	Dial("ip6:ipv6-icmp", "2001:db8::1")
   310  //	Dial("ip6:58", "fe80::1%lo0")
   311  //
   312  // For TCP, UDP and IP networks, if the host is empty or a literal
   313  // unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for
   314  // TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is
   315  // assumed.
   316  //
   317  // For Unix networks, the address must be a file system path.
   318  func Dial(network, address string) (Conn, error) {
   319  	var d Dialer
   320  	return d.Dial(network, address)
   321  }
   322  
   323  // DialTimeout acts like Dial but takes a timeout.
   324  //
   325  // The timeout includes name resolution, if required.
   326  // When using TCP, and the host in the address parameter resolves to
   327  // multiple IP addresses, the timeout is spread over each consecutive
   328  // dial, such that each is given an appropriate fraction of the time
   329  // to connect.
   330  //
   331  // See func Dial for a description of the network and address
   332  // parameters.
   333  func DialTimeout(network, address string, timeout time.Duration) (Conn, error) {
   334  	d := Dialer{Timeout: timeout}
   335  	return d.Dial(network, address)
   336  }
   337  
   338  // sysDialer contains a Dial's parameters and configuration.
   339  type sysDialer struct {
   340  	Dialer
   341  	network, address string
   342  }
   343  
   344  // Dial connects to the address on the named network.
   345  //
   346  // See func Dial for a description of the network and address
   347  // parameters.
   348  func (d *Dialer) Dial(network, address string) (Conn, error) {
   349  	return d.DialContext(context.Background(), network, address)
   350  }
   351  
   352  // DialContext connects to the address on the named network using
   353  // the provided context.
   354  //
   355  // The provided Context must be non-nil. If the context expires before
   356  // the connection is complete, an error is returned. Once successfully
   357  // connected, any expiration of the context will not affect the
   358  // connection.
   359  //
   360  // When using TCP, and the host in the address parameter resolves to multiple
   361  // network addresses, any dial timeout (from d.Timeout or ctx) is spread
   362  // over each consecutive dial, such that each is given an appropriate
   363  // fraction of the time to connect.
   364  // For example, if a host has 4 IP addresses and the timeout is 1 minute,
   365  // the connect to each single address will be given 15 seconds to complete
   366  // before trying the next one.
   367  //
   368  // See func Dial for a description of the network and address
   369  // parameters.
   370  func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error) {
   371  	if ctx == nil {
   372  		panic("nil context")
   373  	}
   374  	deadline := d.deadline(ctx, time.Now())
   375  	if !deadline.IsZero() {
   376  		if d, ok := ctx.Deadline(); !ok || deadline.Before(d) {
   377  			subCtx, cancel := context.WithDeadline(ctx, deadline)
   378  			defer cancel()
   379  			ctx = subCtx
   380  		}
   381  	}
   382  	if oldCancel := d.Cancel; oldCancel != nil {
   383  		subCtx, cancel := context.WithCancel(ctx)
   384  		defer cancel()
   385  		go func() {
   386  			select {
   387  			case <-oldCancel:
   388  				cancel()
   389  			case <-subCtx.Done():
   390  			}
   391  		}()
   392  		ctx = subCtx
   393  	}
   394  
   395  	// Shadow the nettrace (if any) during resolve so Connect events don't fire for DNS lookups.
   396  	resolveCtx := ctx
   397  	if trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace); trace != nil {
   398  		shadow := *trace
   399  		shadow.ConnectStart = nil
   400  		shadow.ConnectDone = nil
   401  		resolveCtx = context.WithValue(resolveCtx, nettrace.TraceKey{}, &shadow)
   402  	}
   403  
   404  	addrs, err := d.resolver().resolveAddrList(resolveCtx, "dial", network, address, d.LocalAddr)
   405  	if err != nil {
   406  		return nil, &OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: err}
   407  	}
   408  
   409  	sd := &sysDialer{
   410  		Dialer:  *d,
   411  		network: network,
   412  		address: address,
   413  	}
   414  
   415  	var primaries, fallbacks addrList
   416  	if d.dualStack() && network == "tcp" {
   417  		primaries, fallbacks = addrs.partition(isIPv4)
   418  	} else {
   419  		primaries = addrs
   420  	}
   421  
   422  	var c Conn
   423  	if len(fallbacks) > 0 {
   424  		c, err = sd.dialParallel(ctx, primaries, fallbacks)
   425  	} else {
   426  		c, err = sd.dialSerial(ctx, primaries)
   427  	}
   428  	if err != nil {
   429  		return nil, err
   430  	}
   431  
   432  	if tc, ok := c.(*TCPConn); ok && d.KeepAlive >= 0 {
   433  		setKeepAlive(tc.fd, true)
   434  		ka := d.KeepAlive
   435  		if d.KeepAlive == 0 {
   436  			ka = defaultTCPKeepAlive
   437  		}
   438  		setKeepAlivePeriod(tc.fd, ka)
   439  		testHookSetKeepAlive(ka)
   440  	}
   441  	return c, nil
   442  }
   443  
   444  // dialParallel races two copies of dialSerial, giving the first a
   445  // head start. It returns the first established connection and
   446  // closes the others. Otherwise it returns an error from the first
   447  // primary address.
   448  func (sd *sysDialer) dialParallel(ctx context.Context, primaries, fallbacks addrList) (Conn, error) {
   449  	if len(fallbacks) == 0 {
   450  		return sd.dialSerial(ctx, primaries)
   451  	}
   452  
   453  	returned := make(chan struct{})
   454  	defer close(returned)
   455  
   456  	type dialResult struct {
   457  		Conn
   458  		error
   459  		primary bool
   460  		done    bool
   461  	}
   462  	results := make(chan dialResult) // unbuffered
   463  
   464  	startRacer := func(ctx context.Context, primary bool) {
   465  		ras := primaries
   466  		if !primary {
   467  			ras = fallbacks
   468  		}
   469  		c, err := sd.dialSerial(ctx, ras)
   470  		select {
   471  		case results <- dialResult{Conn: c, error: err, primary: primary, done: true}:
   472  		case <-returned:
   473  			if c != nil {
   474  				c.Close()
   475  			}
   476  		}
   477  	}
   478  
   479  	var primary, fallback dialResult
   480  
   481  	// Start the main racer.
   482  	primaryCtx, primaryCancel := context.WithCancel(ctx)
   483  	defer primaryCancel()
   484  	go startRacer(primaryCtx, true)
   485  
   486  	// Start the timer for the fallback racer.
   487  	fallbackTimer := time.NewTimer(sd.fallbackDelay())
   488  	defer fallbackTimer.Stop()
   489  
   490  	for {
   491  		select {
   492  		case <-fallbackTimer.C:
   493  			fallbackCtx, fallbackCancel := context.WithCancel(ctx)
   494  			defer fallbackCancel()
   495  			go startRacer(fallbackCtx, false)
   496  
   497  		case res := <-results:
   498  			if res.error == nil {
   499  				return res.Conn, nil
   500  			}
   501  			if res.primary {
   502  				primary = res
   503  			} else {
   504  				fallback = res
   505  			}
   506  			if primary.done && fallback.done {
   507  				return nil, primary.error
   508  			}
   509  			if res.primary && fallbackTimer.Stop() {
   510  				// If we were able to stop the timer, that means it
   511  				// was running (hadn't yet started the fallback), but
   512  				// we just got an error on the primary path, so start
   513  				// the fallback immediately (in 0 nanoseconds).
   514  				fallbackTimer.Reset(0)
   515  			}
   516  		}
   517  	}
   518  }
   519  
   520  // dialSerial connects to a list of addresses in sequence, returning
   521  // either the first successful connection, or the first error.
   522  func (sd *sysDialer) dialSerial(ctx context.Context, ras addrList) (Conn, error) {
   523  	var firstErr error // The error from the first address is most relevant.
   524  
   525  	for i, ra := range ras {
   526  		select {
   527  		case <-ctx.Done():
   528  			return nil, &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: mapErr(ctx.Err())}
   529  		default:
   530  		}
   531  
   532  		dialCtx := ctx
   533  		if deadline, hasDeadline := ctx.Deadline(); hasDeadline {
   534  			partialDeadline, err := partialDeadline(time.Now(), deadline, len(ras)-i)
   535  			if err != nil {
   536  				// Ran out of time.
   537  				if firstErr == nil {
   538  					firstErr = &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: err}
   539  				}
   540  				break
   541  			}
   542  			if partialDeadline.Before(deadline) {
   543  				var cancel context.CancelFunc
   544  				dialCtx, cancel = context.WithDeadline(ctx, partialDeadline)
   545  				defer cancel()
   546  			}
   547  		}
   548  
   549  		c, err := sd.dialSingle(dialCtx, ra)
   550  		if err == nil {
   551  			return c, nil
   552  		}
   553  		if firstErr == nil {
   554  			firstErr = err
   555  		}
   556  	}
   557  
   558  	if firstErr == nil {
   559  		firstErr = &OpError{Op: "dial", Net: sd.network, Source: nil, Addr: nil, Err: errMissingAddress}
   560  	}
   561  	return nil, firstErr
   562  }
   563  
   564  // dialSingle attempts to establish and returns a single connection to
   565  // the destination address.
   566  func (sd *sysDialer) dialSingle(ctx context.Context, ra Addr) (c Conn, err error) {
   567  	trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace)
   568  	if trace != nil {
   569  		raStr := ra.String()
   570  		if trace.ConnectStart != nil {
   571  			trace.ConnectStart(sd.network, raStr)
   572  		}
   573  		if trace.ConnectDone != nil {
   574  			defer func() { trace.ConnectDone(sd.network, raStr, err) }()
   575  		}
   576  	}
   577  	la := sd.LocalAddr
   578  	switch ra := ra.(type) {
   579  	case *TCPAddr:
   580  		la, _ := la.(*TCPAddr)
   581  		c, err = sd.dialTCP(ctx, la, ra)
   582  	case *UDPAddr:
   583  		la, _ := la.(*UDPAddr)
   584  		c, err = sd.dialUDP(ctx, la, ra)
   585  	case *IPAddr:
   586  		la, _ := la.(*IPAddr)
   587  		c, err = sd.dialIP(ctx, la, ra)
   588  	case *UnixAddr:
   589  		la, _ := la.(*UnixAddr)
   590  		c, err = sd.dialUnix(ctx, la, ra)
   591  	default:
   592  		return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: &AddrError{Err: "unexpected address type", Addr: sd.address}}
   593  	}
   594  	if err != nil {
   595  		return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: err} // c is non-nil interface containing nil pointer
   596  	}
   597  	return c, nil
   598  }
   599  
   600  // ListenConfig contains options for listening to an address.
   601  type ListenConfig struct {
   602  	// If Control is not nil, it is called after creating the network
   603  	// connection but before binding it to the operating system.
   604  	//
   605  	// Network and address parameters passed to Control method are not
   606  	// necessarily the ones passed to Listen. For example, passing "tcp" to
   607  	// Listen will cause the Control function to be called with "tcp4" or "tcp6".
   608  	Control func(network, address string, c syscall.RawConn) error
   609  
   610  	// KeepAlive specifies the keep-alive period for network
   611  	// connections accepted by this listener.
   612  	// If zero, keep-alives are enabled if supported by the protocol
   613  	// and operating system. Network protocols or operating systems
   614  	// that do not support keep-alives ignore this field.
   615  	// If negative, keep-alives are disabled.
   616  	KeepAlive time.Duration
   617  }
   618  
   619  // Listen announces on the local network address.
   620  //
   621  // See func Listen for a description of the network and address
   622  // parameters.
   623  func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error) {
   624  	addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil)
   625  	if err != nil {
   626  		return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err}
   627  	}
   628  	sl := &sysListener{
   629  		ListenConfig: *lc,
   630  		network:      network,
   631  		address:      address,
   632  	}
   633  	var l Listener
   634  	la := addrs.first(isIPv4)
   635  	switch la := la.(type) {
   636  	case *TCPAddr:
   637  		l, err = sl.listenTCP(ctx, la)
   638  	case *UnixAddr:
   639  		l, err = sl.listenUnix(ctx, la)
   640  	default:
   641  		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}}
   642  	}
   643  	if err != nil {
   644  		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // l is non-nil interface containing nil pointer
   645  	}
   646  	return l, nil
   647  }
   648  
   649  // ListenPacket announces on the local network address.
   650  //
   651  // See func ListenPacket for a description of the network and address
   652  // parameters.
   653  func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error) {
   654  	addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil)
   655  	if err != nil {
   656  		return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err}
   657  	}
   658  	sl := &sysListener{
   659  		ListenConfig: *lc,
   660  		network:      network,
   661  		address:      address,
   662  	}
   663  	var c PacketConn
   664  	la := addrs.first(isIPv4)
   665  	switch la := la.(type) {
   666  	case *UDPAddr:
   667  		c, err = sl.listenUDP(ctx, la)
   668  	case *IPAddr:
   669  		c, err = sl.listenIP(ctx, la)
   670  	case *UnixAddr:
   671  		c, err = sl.listenUnixgram(ctx, la)
   672  	default:
   673  		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}}
   674  	}
   675  	if err != nil {
   676  		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // c is non-nil interface containing nil pointer
   677  	}
   678  	return c, nil
   679  }
   680  
   681  // sysListener contains a Listen's parameters and configuration.
   682  type sysListener struct {
   683  	ListenConfig
   684  	network, address string
   685  }
   686  
   687  // Listen announces on the local network address.
   688  //
   689  // The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket".
   690  //
   691  // For TCP networks, if the host in the address parameter is empty or
   692  // a literal unspecified IP address, Listen listens on all available
   693  // unicast and anycast IP addresses of the local system.
   694  // To only use IPv4, use network "tcp4".
   695  // The address can use a host name, but this is not recommended,
   696  // because it will create a listener for at most one of the host's IP
   697  // addresses.
   698  // If the port in the address parameter is empty or "0", as in
   699  // "127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
   700  // The Addr method of Listener can be used to discover the chosen
   701  // port.
   702  //
   703  // See func Dial for a description of the network and address
   704  // parameters.
   705  func Listen(network, address string) (Listener, error) {
   706  	var lc ListenConfig
   707  	return lc.Listen(context.Background(), network, address)
   708  }
   709  
   710  // ListenPacket announces on the local network address.
   711  //
   712  // The network must be "udp", "udp4", "udp6", "unixgram", or an IP
   713  // transport. The IP transports are "ip", "ip4", or "ip6" followed by
   714  // a colon and a literal protocol number or a protocol name, as in
   715  // "ip:1" or "ip:icmp".
   716  //
   717  // For UDP and IP networks, if the host in the address parameter is
   718  // empty or a literal unspecified IP address, ListenPacket listens on
   719  // all available IP addresses of the local system except multicast IP
   720  // addresses.
   721  // To only use IPv4, use network "udp4" or "ip4:proto".
   722  // The address can use a host name, but this is not recommended,
   723  // because it will create a listener for at most one of the host's IP
   724  // addresses.
   725  // If the port in the address parameter is empty or "0", as in
   726  // "127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
   727  // The LocalAddr method of PacketConn can be used to discover the
   728  // chosen port.
   729  //
   730  // See func Dial for a description of the network and address
   731  // parameters.
   732  func ListenPacket(network, address string) (PacketConn, error) {
   733  	var lc ListenConfig
   734  	return lc.ListenPacket(context.Background(), network, address)
   735  }
   736  

View as plain text