Skip to content
class method

Socket.tcp

(::String host, ::Integer port, ?::String local_host, ?::Integer local_port, ?resolv_timeout: ::Time::_Timeout, ?connect_timeout: ::Time::_Timeout) -> instance
(::String host, ::Integer port, ?::String local_host, ?::Integer local_port, ?open_timeout: ::Time::_Timeout) -> instance
[T] (::String host, ::Integer port, ?::String local_host, ?::Integer local_port, ?resolv_timeout: ::Time::_Timeout, ?connect_timeout: ::Time::_Timeout) { (instance) -> T } -> T
[T] (::String host, ::Integer port, ?::String local_host, ?::Integer local_port, ?open_timeout: ::Time::_Timeout) { (instance) -> T } -> T
Socket.tcp(host, port, local_host=nil, local_port=nil, [opts]) {|socket| ... }
Socket.tcp(host, port, local_host=nil, local_port=nil, [opts])

creates a new socket object connected to host:port using TCP/IP.

Starting from Ruby 3.4, this method operates according to the Happy Eyeballs Version 2 (RFC 8305) algorithm by default.

For details on Happy Eyeballs Version 2, see Socket.tcp_fast_fallback=.

To make it behave the same as in Ruby 3.3 and earlier, explicitly specify the option fast_fallback:false. Or, setting Socket.tcp_fast_fallback=false will disable Happy Eyeballs Version 2 not only for this method but for all Socket globally.

If local_host:local_port is given, the socket is bound to it.

The optional last argument opts is options represented by a hash. opts may have following options:

:resolv_timeout

Specifies the timeout in seconds from when the hostname resolution starts.

:connect_timeout

This method sequentially attempts connecting to all candidate destination addresses.
The connect_timeout specifies the timeout in seconds from the start of the connection attempt to the last candidate.
By default, all connection attempts continue until the timeout occurs.
When fast_fallback:false is explicitly specified,
a timeout is set for each connection attempt and any connection attempt that exceeds its timeout will be canceled.



:open_timeout

Specifies the timeout in seconds from the start of the method execution.
If this timeout is reached while there are still addresses that have not yet been attempted for connection, no further attempts will be made.
If this option is specified together with other timeout options, an ArgumentError will be raised.

:fast_fallback

Enables the Happy Eyeballs Version 2 algorithm (enabled by default).

If a block is given, the block is called with the socket. The value of the block is returned. The socket is closed when this method returns.

If no block is given, the socket is returned.

Example
Socket.tcp("www.ruby-lang.org", 80) {|sock|
  sock.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
  sock.close_write
  puts sock.read
}

Ruby version changes

  1. 4.0