github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/net/dial.go (about) 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 "syscall" 11 "time" 12 ) 13 14 // defaultTCPKeepAlive is a default constant value for TCPKeepAlive times 15 // See golang.org/issue/31510 16 const ( 17 defaultTCPKeepAlive = 15 * time.Second 18 ) 19 20 // A Dialer contains options for connecting to an address. 21 // 22 // The zero value for each field is equivalent to dialing 23 // without that option. Dialing with the zero value of Dialer 24 // is therefore equivalent to just calling the Dial function. 25 // 26 // It is safe to call Dialer's methods concurrently. 27 type Dialer struct { 28 // Timeout is the maximum amount of time a dial will wait for 29 // a connect to complete. If Deadline is also set, it may fail 30 // earlier. 31 // 32 // The default is no timeout. 33 // 34 // When using TCP and dialing a host name with multiple IP 35 // addresses, the timeout may be divided between them. 36 // 37 // With or without a timeout, the operating system may impose 38 // its own earlier timeout. For instance, TCP timeouts are 39 // often around 3 minutes. 40 Timeout time.Duration 41 42 // Deadline is the absolute point in time after which dials 43 // will fail. If Timeout is set, it may fail earlier. 44 // Zero means no deadline, or dependent on the operating system 45 // as with the Timeout option. 46 Deadline time.Time 47 48 // LocalAddr is the local address to use when dialing an 49 // address. The address must be of a compatible type for the 50 // network being dialed. 51 // If nil, a local address is automatically chosen. 52 LocalAddr Addr 53 54 // DualStack previously enabled RFC 6555 Fast Fallback 55 // support, also known as "Happy Eyeballs", in which IPv4 is 56 // tried soon if IPv6 appears to be misconfigured and 57 // hanging. 58 // 59 // Deprecated: Fast Fallback is enabled by default. To 60 // disable, set FallbackDelay to a negative value. 61 DualStack bool 62 63 // FallbackDelay specifies the length of time to wait before 64 // spawning a RFC 6555 Fast Fallback connection. That is, this 65 // is the amount of time to wait for IPv6 to succeed before 66 // assuming that IPv6 is misconfigured and falling back to 67 // IPv4. 68 // 69 // If zero, a default delay of 300ms is used. 70 // A negative value disables Fast Fallback support. 71 FallbackDelay time.Duration 72 73 // KeepAlive specifies the interval between keep-alive 74 // probes for an active network connection. 75 // If zero, keep-alive probes are sent with a default value 76 // (currently 15 seconds), if supported by the protocol and operating 77 // system. Network protocols or operating systems that do 78 // not support keep-alives ignore this field. 79 // If negative, keep-alive probes are disabled. 80 KeepAlive time.Duration 81 82 // Resolver optionally specifies an alternate resolver to use. 83 Resolver *Resolver 84 85 // Cancel is an optional channel whose closure indicates that 86 // the dial should be canceled. Not all types of dials support 87 // cancellation. 88 // 89 // Deprecated: Use DialContext instead. 90 Cancel <-chan struct{} 91 92 // If Control is not nil, it is called after creating the network 93 // connection but before actually dialing. 94 // 95 // Network and address parameters passed to Control method are not 96 // necessarily the ones passed to Dial. For example, passing "tcp" to Dial 97 // will cause the Control function to be called with "tcp4" or "tcp6". 98 Control func(network, address string, c syscall.RawConn) error 99 } 100 101 func (d *Dialer) dualStack() bool { return d.FallbackDelay >= 0 } 102 103 func minNonzeroTime(a, b time.Time) time.Time { 104 if a.IsZero() { 105 return b 106 } 107 if b.IsZero() || a.Before(b) { 108 return a 109 } 110 return b 111 } 112 113 // deadline returns the earliest of: 114 // - now+Timeout 115 // - d.Deadline 116 // - the context's deadline 117 // 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{}, 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 // 294 // Dial("tcp", "golang.org:http") 295 // Dial("tcp", "192.0.2.1:http") 296 // Dial("tcp", "198.51.100.1:80") 297 // Dial("udp", "[2001:db8::1]:domain") 298 // Dial("udp", "[fe80::1%lo0]:53") 299 // Dial("tcp", ":80") 300 // 301 // For IP networks, the network must be "ip", "ip4" or "ip6" followed 302 // by a colon and a literal protocol number or a protocol name, and 303 // the address has the form "host". The host must be a literal IP 304 // address or a literal IPv6 address with zone. 305 // It depends on each operating system how the operating system 306 // behaves with a non-well known protocol number such as "0" or "255". 307 // 308 // Examples: 309 // 310 // Dial("ip4:1", "192.0.2.1") 311 // Dial("ip6:ipv6-icmp", "2001:db8::1") 312 // Dial("ip6:58", "fe80::1%lo0") 313 // 314 // For TCP, UDP and IP networks, if the host is empty or a literal 315 // unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for 316 // TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is 317 // assumed. 318 // 319 // For Unix networks, the address must be a file system path. 320 func Dial(network, address string) (Conn, error) { 321 var d Dialer 322 return d.Dial(network, address) 323 } 324 325 // DialTimeout acts like Dial but takes a timeout. 326 // 327 // The timeout includes name resolution, if required. 328 // When using TCP, and the host in the address parameter resolves to 329 // multiple IP addresses, the timeout is spread over each consecutive 330 // dial, such that each is given an appropriate fraction of the time 331 // to connect. 332 // 333 // See func Dial for a description of the network and address 334 // parameters. 335 func DialTimeout(network, address string, timeout time.Duration) (Conn, error) { 336 d := Dialer{Timeout: timeout} 337 return d.Dial(network, address) 338 } 339 340 // sysDialer contains a Dial's parameters and configuration. 341 type sysDialer struct { 342 Dialer 343 network, address string 344 testHookDialTCP func(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, error) 345 } 346 347 // Dial connects to the address on the named network. 348 // 349 // See func Dial for a description of the network and address 350 // parameters. 351 // 352 // Dial uses context.Background internally; to specify the context, use 353 // DialContext. 354 func (d *Dialer) Dial(network, address string) (Conn, error) { 355 return d.DialContext(context.Background(), network, address) 356 } 357 358 // DialContext connects to the address on the named network using 359 // the provided context. 360 // 361 // The provided Context must be non-nil. If the context expires before 362 // the connection is complete, an error is returned. Once successfully 363 // connected, any expiration of the context will not affect the 364 // connection. 365 // 366 // When using TCP, and the host in the address parameter resolves to multiple 367 // network addresses, any dial timeout (from d.Timeout or ctx) is spread 368 // over each consecutive dial, such that each is given an appropriate 369 // fraction of the time to connect. 370 // For example, if a host has 4 IP addresses and the timeout is 1 minute, 371 // the connect to each single address will be given 15 seconds to complete 372 // before trying the next one. 373 // 374 // See func Dial for a description of the network and address 375 // parameters. 376 func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error) { 377 if ctx == nil { 378 panic("nil context") 379 } 380 deadline := d.deadline(ctx, time.Now()) 381 if !deadline.IsZero() { 382 if d, ok := ctx.Deadline(); !ok || deadline.Before(d) { 383 subCtx, cancel := context.WithDeadline(ctx, deadline) 384 defer cancel() 385 ctx = subCtx 386 } 387 } 388 if oldCancel := d.Cancel; oldCancel != nil { 389 subCtx, cancel := context.WithCancel(ctx) 390 defer cancel() 391 go func() { 392 select { 393 case <-oldCancel: 394 cancel() 395 case <-subCtx.Done(): 396 } 397 }() 398 ctx = subCtx 399 } 400 401 // Shadow the nettrace (if any) during resolve so Connect events don't fire for DNS lookups. 402 resolveCtx := ctx 403 if trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace); trace != nil { 404 shadow := *trace 405 shadow.ConnectStart = nil 406 shadow.ConnectDone = nil 407 resolveCtx = context.WithValue(resolveCtx, nettrace.TraceKey{}, &shadow) 408 } 409 410 addrs, err := d.resolver().resolveAddrList(resolveCtx, "dial", network, address, d.LocalAddr) 411 if err != nil { 412 return nil, &OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: err} 413 } 414 415 sd := &sysDialer{ 416 Dialer: *d, 417 network: network, 418 address: address, 419 } 420 421 var primaries, fallbacks addrList 422 if d.dualStack() && network == "tcp" { 423 primaries, fallbacks = addrs.partition(isIPv4) 424 } else { 425 primaries = addrs 426 } 427 428 c, err := sd.dialParallel(ctx, primaries, fallbacks) 429 if err != nil { 430 return nil, err 431 } 432 433 if tc, ok := c.(*TCPConn); ok && d.KeepAlive >= 0 { 434 setKeepAlive(tc.fd, true) 435 ka := d.KeepAlive 436 if d.KeepAlive == 0 { 437 ka = defaultTCPKeepAlive 438 } 439 setKeepAlivePeriod(tc.fd, ka) 440 testHookSetKeepAlive(ka) 441 } 442 return c, nil 443 } 444 445 // dialParallel races two copies of dialSerial, giving the first a 446 // head start. It returns the first established connection and 447 // closes the others. Otherwise it returns an error from the first 448 // primary address. 449 func (sd *sysDialer) dialParallel(ctx context.Context, primaries, fallbacks addrList) (Conn, error) { 450 if len(fallbacks) == 0 { 451 return sd.dialSerial(ctx, primaries) 452 } 453 454 returned := make(chan struct{}) 455 defer close(returned) 456 457 type dialResult struct { 458 Conn 459 error 460 primary bool 461 done bool 462 } 463 results := make(chan dialResult) // unbuffered 464 465 startRacer := func(ctx context.Context, primary bool) { 466 ras := primaries 467 if !primary { 468 ras = fallbacks 469 } 470 c, err := sd.dialSerial(ctx, ras) 471 select { 472 case results <- dialResult{Conn: c, error: err, primary: primary, done: true}: 473 case <-returned: 474 if c != nil { 475 c.Close() 476 } 477 } 478 } 479 480 var primary, fallback dialResult 481 482 // Start the main racer. 483 primaryCtx, primaryCancel := context.WithCancel(ctx) 484 defer primaryCancel() 485 go startRacer(primaryCtx, true) 486 487 // Start the timer for the fallback racer. 488 fallbackTimer := time.NewTimer(sd.fallbackDelay()) 489 defer fallbackTimer.Stop() 490 491 for { 492 select { 493 case <-fallbackTimer.C: 494 fallbackCtx, fallbackCancel := context.WithCancel(ctx) 495 defer fallbackCancel() 496 go startRacer(fallbackCtx, false) 497 498 case res := <-results: 499 if res.error == nil { 500 return res.Conn, nil 501 } 502 if res.primary { 503 primary = res 504 } else { 505 fallback = res 506 } 507 if primary.done && fallback.done { 508 return nil, primary.error 509 } 510 if res.primary && fallbackTimer.Stop() { 511 // If we were able to stop the timer, that means it 512 // was running (hadn't yet started the fallback), but 513 // we just got an error on the primary path, so start 514 // the fallback immediately (in 0 nanoseconds). 515 fallbackTimer.Reset(0) 516 } 517 } 518 } 519 } 520 521 // dialSerial connects to a list of addresses in sequence, returning 522 // either the first successful connection, or the first error. 523 func (sd *sysDialer) dialSerial(ctx context.Context, ras addrList) (Conn, error) { 524 var firstErr error // The error from the first address is most relevant. 525 526 for i, ra := range ras { 527 select { 528 case <-ctx.Done(): 529 return nil, &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: mapErr(ctx.Err())} 530 default: 531 } 532 533 dialCtx := ctx 534 if deadline, hasDeadline := ctx.Deadline(); hasDeadline { 535 partialDeadline, err := partialDeadline(time.Now(), deadline, len(ras)-i) 536 if err != nil { 537 // Ran out of time. 538 if firstErr == nil { 539 firstErr = &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: err} 540 } 541 break 542 } 543 if partialDeadline.Before(deadline) { 544 var cancel context.CancelFunc 545 dialCtx, cancel = context.WithDeadline(ctx, partialDeadline) 546 defer cancel() 547 } 548 } 549 550 c, err := sd.dialSingle(dialCtx, ra) 551 if err == nil { 552 return c, nil 553 } 554 if firstErr == nil { 555 firstErr = err 556 } 557 } 558 559 if firstErr == nil { 560 firstErr = &OpError{Op: "dial", Net: sd.network, Source: nil, Addr: nil, Err: errMissingAddress} 561 } 562 return nil, firstErr 563 } 564 565 // dialSingle attempts to establish and returns a single connection to 566 // the destination address. 567 func (sd *sysDialer) dialSingle(ctx context.Context, ra Addr) (c Conn, err error) { 568 trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace) 569 if trace != nil { 570 raStr := ra.String() 571 if trace.ConnectStart != nil { 572 trace.ConnectStart(sd.network, raStr) 573 } 574 if trace.ConnectDone != nil { 575 defer func() { trace.ConnectDone(sd.network, raStr, err) }() 576 } 577 } 578 la := sd.LocalAddr 579 switch ra := ra.(type) { 580 case *TCPAddr: 581 la, _ := la.(*TCPAddr) 582 c, err = sd.dialTCP(ctx, la, ra) 583 case *UDPAddr: 584 la, _ := la.(*UDPAddr) 585 c, err = sd.dialUDP(ctx, la, ra) 586 case *IPAddr: 587 la, _ := la.(*IPAddr) 588 c, err = sd.dialIP(ctx, la, ra) 589 case *UnixAddr: 590 la, _ := la.(*UnixAddr) 591 c, err = sd.dialUnix(ctx, la, ra) 592 default: 593 return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: &AddrError{Err: "unexpected address type", Addr: sd.address}} 594 } 595 if err != nil { 596 return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: err} // c is non-nil interface containing nil pointer 597 } 598 return c, nil 599 } 600 601 // ListenConfig contains options for listening to an address. 602 type ListenConfig struct { 603 // If Control is not nil, it is called after creating the network 604 // connection but before binding it to the operating system. 605 // 606 // Network and address parameters passed to Control method are not 607 // necessarily the ones passed to Listen. For example, passing "tcp" to 608 // Listen will cause the Control function to be called with "tcp4" or "tcp6". 609 Control func(network, address string, c syscall.RawConn) error 610 611 // KeepAlive specifies the keep-alive period for network 612 // connections accepted by this listener. 613 // If zero, keep-alives are enabled if supported by the protocol 614 // and operating system. Network protocols or operating systems 615 // that do not support keep-alives ignore this field. 616 // If negative, keep-alives are disabled. 617 KeepAlive time.Duration 618 } 619 620 // Listen announces on the local network address. 621 // 622 // See func Listen for a description of the network and address 623 // parameters. 624 func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error) { 625 addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil) 626 if err != nil { 627 return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err} 628 } 629 sl := &sysListener{ 630 ListenConfig: *lc, 631 network: network, 632 address: address, 633 } 634 var l Listener 635 la := addrs.first(isIPv4) 636 switch la := la.(type) { 637 case *TCPAddr: 638 l, err = sl.listenTCP(ctx, la) 639 case *UnixAddr: 640 l, err = sl.listenUnix(ctx, la) 641 default: 642 return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}} 643 } 644 if err != nil { 645 return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // l is non-nil interface containing nil pointer 646 } 647 return l, nil 648 } 649 650 // ListenPacket announces on the local network address. 651 // 652 // See func ListenPacket for a description of the network and address 653 // parameters. 654 func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error) { 655 addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil) 656 if err != nil { 657 return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err} 658 } 659 sl := &sysListener{ 660 ListenConfig: *lc, 661 network: network, 662 address: address, 663 } 664 var c PacketConn 665 la := addrs.first(isIPv4) 666 switch la := la.(type) { 667 case *UDPAddr: 668 c, err = sl.listenUDP(ctx, la) 669 case *IPAddr: 670 c, err = sl.listenIP(ctx, la) 671 case *UnixAddr: 672 c, err = sl.listenUnixgram(ctx, la) 673 default: 674 return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}} 675 } 676 if err != nil { 677 return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // c is non-nil interface containing nil pointer 678 } 679 return c, nil 680 } 681 682 // sysListener contains a Listen's parameters and configuration. 683 type sysListener struct { 684 ListenConfig 685 network, address string 686 } 687 688 // Listen announces on the local network address. 689 // 690 // The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket". 691 // 692 // For TCP networks, if the host in the address parameter is empty or 693 // a literal unspecified IP address, Listen listens on all available 694 // unicast and anycast IP addresses of the local system. 695 // To only use IPv4, use network "tcp4". 696 // The address can use a host name, but this is not recommended, 697 // because it will create a listener for at most one of the host's IP 698 // addresses. 699 // If the port in the address parameter is empty or "0", as in 700 // "127.0.0.1:" or "[::1]:0", a port number is automatically chosen. 701 // The Addr method of Listener can be used to discover the chosen 702 // port. 703 // 704 // See func Dial for a description of the network and address 705 // parameters. 706 // 707 // Listen uses context.Background internally; to specify the context, use 708 // ListenConfig.Listen. 709 func Listen(network, address string) (Listener, error) { 710 var lc ListenConfig 711 return lc.Listen(context.Background(), network, address) 712 } 713 714 // ListenPacket announces on the local network address. 715 // 716 // The network must be "udp", "udp4", "udp6", "unixgram", or an IP 717 // transport. The IP transports are "ip", "ip4", or "ip6" followed by 718 // a colon and a literal protocol number or a protocol name, as in 719 // "ip:1" or "ip:icmp". 720 // 721 // For UDP and IP networks, if the host in the address parameter is 722 // empty or a literal unspecified IP address, ListenPacket listens on 723 // all available IP addresses of the local system except multicast IP 724 // addresses. 725 // To only use IPv4, use network "udp4" or "ip4:proto". 726 // The address can use a host name, but this is not recommended, 727 // because it will create a listener for at most one of the host's IP 728 // addresses. 729 // If the port in the address parameter is empty or "0", as in 730 // "127.0.0.1:" or "[::1]:0", a port number is automatically chosen. 731 // The LocalAddr method of PacketConn can be used to discover the 732 // chosen port. 733 // 734 // See func Dial for a description of the network and address 735 // parameters. 736 // 737 // ListenPacket uses context.Background internally; to specify the context, use 738 // ListenConfig.ListenPacket. 739 func ListenPacket(network, address string) (PacketConn, error) { 740 var lc ListenConfig 741 return lc.ListenPacket(context.Background(), network, address) 742 }