Method: Async::IO::Socket.connect

Defined in:
lib/async/io/socket.rb

.connect(remote_address, local_address: nil, task: Task.current, **options) ⇒ Object

Establish a connection to a given ‘remote_address`.

Examples:

socket = Async::IO::Socket.connect(Async::IO::Address.tcp("8.8.8.8", 53))

Parameters:

  • remote_address (Address)

    The remote address to connect to.

  • local_address (Hash) (defaults to: nil)

    a customizable set of options

Options Hash (local_address:):

  • The (Address)

    local address to bind to before connecting.


118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/async/io/socket.rb', line 118

def self.connect(remote_address, local_address: nil, task: Task.current, **options)
	Console.logger.debug(self) {"Connecting to #{remote_address.inspect}"}
	
	task.annotate "connecting to #{remote_address.inspect}"
	
	wrapper = build(remote_address.afamily, remote_address.socktype, remote_address.protocol, **options) do |socket|
		if local_address
			if defined?(IP_BIND_ADDRESS_NO_PORT)
				# Inform the kernel (Linux 4.2+) to not reserve an ephemeral port when using bind(2) with a port number of 0. The port will later be automatically chosen at connect(2) time, in a way that allows sharing a source port as long as the 4-tuple is unique.
				socket.setsockopt(SOL_IP, IP_BIND_ADDRESS_NO_PORT, 1)
			end
			
			socket.bind(local_address.to_sockaddr)
		end
	end
	
	begin
		wrapper.connect(remote_address.to_sockaddr)
		task.annotate "connected to #{remote_address.inspect} [fd=#{wrapper.fileno}]"
	rescue Exception
		wrapper.close
		raise
	end
	
	return wrapper unless block_given?
	
	begin
		yield wrapper, task
	ensure
		wrapper.close
	end
end