Project

General

Profile

Feature #8042 ยป addrinfo.socket.2.patch

Addrinfo#unbound_socket - drbrain (Eric Hodel), 03/12/2013 02:18 AM

View differences:

ext/socket/lib/socket.rb (working copy)
45 45
  # If a block is given the created socket is yielded for each address.
46 46
  #
47 47
  def connect_internal(local_addrinfo, timeout=nil) # :yields: socket
48
    sock = Socket.new(self.pfamily, self.socktype, self.protocol)
48
    sock = self.unbound_socket
49 49
    begin
50 50
      sock.ipv6only! if self.ipv6?
51 51
      sock.bind local_addrinfo if local_addrinfo
......
172 172
  #   }
173 173
  #
174 174
  def bind
175
    sock = Socket.new(self.pfamily, self.socktype, self.protocol)
175
    sock = self.unbound_socket
176 176
    begin
177 177
      sock.ipv6only! if self.ipv6?
178 178
      sock.setsockopt(:SOCKET, :REUSEADDR, 1)
......
189 189

  
190 190
  # creates a listening socket bound to self.
191 191
  def listen(backlog=Socket::SOMAXCONN)
192
    sock = Socket.new(self.pfamily, self.socktype, self.protocol)
192
    sock = self.unbound_socket
193 193
    begin
194 194
      sock.ipv6only! if self.ipv6?
195 195
      sock.setsockopt(:SOCKET, :REUSEADDR, 1)
......
205 205
    end
206 206
  end
207 207

  
208
  # Creates a socket from Addrinfo that is not bound or connected.
209
  #
210
  # Note that you must have set a protocol family in Addrinfo.new or by using
211
  # Addrinfo.udp or Addrinfo.tcp.
212
  def unbound_socket
213
    Socket.new(self.pfamily, self.socktype, self.protocol)
214
  end
215

  
208 216
  # iterates over the list of Addrinfo objects obtained by Addrinfo.getaddrinfo.
209 217
  #
210 218
  #   Addrinfo.foreach(nil, 80) {|x| p x }
......
358 366
      port = nil
359 367
      ai_list.each {|ai|
360 368
        begin
361
          s = Socket.new(ai.pfamily, ai.socktype, ai.protocol)
369
          s = ai.unbound_socket
362 370
        rescue SystemCallError
363 371
          next
364 372
        end
test/socket/test_addrinfo.rb (working copy)
120 120
    s2.close if s2 && !s2.closed?
121 121
  end
122 122

  
123
  def test_unbound_socket
124
    s1 = Socket.new(:INET, :DGRAM, 0)
125
    sa = Socket.sockaddr_in(0, "127.0.0.1")
126
    ai = Addrinfo.udp("127.0.0.1", 0)
127
    s1.bind ai
128

  
129
    s2 = ai.unbound_socket
130
    s2.send("test-socket", 0, s1.getsockname)
131
    assert_equal("test-socket", s1.recv(100))
132
  ensure
133
    s1.close if s1 && !s1.closed?
134
    s2.close if s2 && !s2.closed?
135
  end
136

  
123 137
  def test_socket_bind
124 138
    s1 = Socket.new(:INET, :DGRAM, 0)
125 139
    sa = Socket.sockaddr_in(0, "127.0.0.1")