require 'socket.jar'
class Addrinfo
# creates an Addrinfo object from the arguments.
#
# The arguments are interpreted as similar to self.
#
# Addrinfo.tcp("0.0.0.0", 4649).family_addrinfo("www.ruby-lang.org", 80)
# #=> #<Addrinfo: 221.186.184.68:80 TCP (www.ruby-lang.org:80)>
#
# Addrinfo.unix("/tmp/sock").family_addrinfo("/tmp/sock2")
# #=> #<Addrinfo: /tmp/sock2 SOCK_STREAM>
#
def family_addrinfo(*args)
if args.empty?
raise ArgumentError, "no address specified"
elsif Addrinfo === args.first
raise ArgumentError, "too many arguments" if args.length != 1
elsif self.ip?
raise ArgumentError, "IP address needs host and port but #{args.length} arguments given" if args.length != 2
host, port = args
Addrinfo.getaddrinfo(host, port, self.pfamily, self.socktype, self.protocol)[0]
elsif self.unix?
raise ArgumentError, "UNIX socket needs single path argument but #{args.length} arguments given" if args.length != 1
path, = args
Addrinfo.unix(path)
else
raise ArgumentError, "unexpected family"
end
end
# creates a new Socket connected to the address of +local_addrinfo+.
#
# If no arguments are given, the address of the socket is not bound.
#
# If a block is given the created socket is yielded for each address.
#
def connect_internal(local_addrinfo) # :yields: socket
sock = Socket.new(self.pfamily, self.socktype, self.protocol)
begin
sock.ipv6only! if self.ipv6?
sock.bind local_addrinfo if local_addrinfo
sock.connect(self)
rescue Exception
sock.close
raise
end
if block_given?
begin
yield sock
ensure
sock.close if !sock.closed?
end
else
sock
end
end
private :connect_internal
# creates a socket connected to the address of self.
#
# If one or more arguments given as _local_addr_args_,
# it is used as the local address of the socket.
# _local_addr_args_ is given for family_addrinfo to obtain actual address.
#
# If no arguments given, the local address of the socket is not bound.
#
# If a block is given, it is called with the socket and the value of the block is returned.
# The socket is returned otherwise.
#
# Addrinfo.tcp("www.ruby-lang.org", 80).connect_from("0.0.0.0", 4649) {|s|
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
# puts s.read
# }
#
# # Addrinfo object can be taken for the argument.
# Addrinfo.tcp("www.ruby-lang.org", 80).connect_from(Addrinfo.tcp("0.0.0.0", 4649)) {|s|
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
# puts s.read
# }
#
def connect_from(*local_addr_args, &block)
connect_internal(family_addrinfo(*local_addr_args), &block)
end
# creates a socket connected to the address of self.
#
# If a block is given, it is called with the socket and the value of the block is returned.
# The socket is returned otherwise.
#
# Addrinfo.tcp("www.ruby-lang.org", 80).connect {|s|
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
# puts s.read
# }
#
def connect(&block)
connect_internal(nil, &block)
end
# creates a socket connected to _remote_addr_args_ and bound to self.
#
# If a block is given, it is called with the socket and the value of the block is returned.
# The socket is returned otherwise.
#
# Addrinfo.tcp("0.0.0.0", 4649).connect_to("www.ruby-lang.org", 80) {|s|
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
# puts s.read
# }
#
def connect_to(*remote_addr_args, &block)
remote_addrinfo = family_addrinfo(*remote_addr_args)
remote_addrinfo.send(:connect_internal, self, &block)
end
# creates a socket bound to self.
#
# If a block is given, it is called with the socket and the value of the block is returned.
# The socket is returned otherwise.
#
# Addrinfo.udp("0.0.0.0", 9981).bind {|s|
# s.local_address.connect {|s| s.send "hello", 0 }
# p s.recv(10) #=> "hello"
# }
#
def bind
sock = Socket.new(self.pfamily, self.socktype, self.protocol)
begin
sock.ipv6only! if self.ipv6?
sock.setsockopt(:SOCKET, :REUSEADDR, 1)
sock.bind(self)
rescue Exception
sock.close
raise
end
if block_given?
begin
yield sock
ensure
sock.close if !sock.closed?
end
else
sock
end
end
# creates a listening socket bound to self.
def listen(backlog=5)
sock = Socket.new(self.pfamily, self.socktype, self.protocol)
begin
sock.ipv6only! if self.ipv6?
sock.setsockopt(:SOCKET, :REUSEADDR, 1)
sock.bind(self)
sock.listen(backlog)
rescue Exception
sock.close
raise
end
if block_given?
begin
yield sock
ensure
sock.close if !sock.closed?
end
else
sock
end
end
# iterates over the list of Addrinfo objects obtained by Addrinfo.getaddrinfo.
#
# Addrinfo.foreach(nil, 80) {|x| p x }
# #=> #<Addrinfo: 127.0.0.1:80 TCP (:80)>
# # #<Addrinfo: 127.0.0.1:80 UDP (:80)>
# # #<Addrinfo: [::1]:80 TCP (:80)>
# # #<Addrinfo: [::1]:80 UDP (:80)>
#
def self.foreach(nodename, service, family=nil, socktype=nil, protocol=nil, flags=nil, &block)
Addrinfo.getaddrinfo(nodename, service, family, socktype, protocol, flags).each(&block)
end
end
class BasicSocket < IO
# Returns an address of the socket suitable for connect in the local machine.
#
# This method returns _self_.local_address, except following condition.
#
# - IPv4 unspecified address (0.0.0.0) is replaced by IPv4 loopback address (127.0.0.1).
# - IPv6 unspecified address (::) is replaced by IPv6 loopback address (::1).
#
# If the local address is not suitable for connect, SocketError is raised.
# IPv4 and IPv6 address which port is 0 is not suitable for connect.
# Unix domain socket which has no path is not suitable for connect.
#
# Addrinfo.tcp("0.0.0.0", 0).listen {|serv|
# p serv.connect_address #=> #<Addrinfo: 127.0.0.1:53660 TCP>
# serv.connect_address.connect {|c|
# s, _ = serv.accept
# p [c, s] #=> [#<Socket:fd 4>, #<Socket:fd 6>]
# }
# }
#
def connect_address
addr = local_address
afamily = addr.afamily
if afamily == Socket::AF_INET
raise SocketError, "unbound IPv4 socket" if addr.ip_port == 0
if addr.ip_address == "0.0.0.0"
addr = Addrinfo.new(["AF_INET", addr.ip_port, nil, "127.0.0.1"], addr.pfamily, addr.socktype, addr.protocol)
end
elsif defined?(Socket::AF_INET6) && afamily == Socket::AF_INET6
raise SocketError, "unbound IPv6 socket" if addr.ip_port == 0
if addr.ip_address == "::"
addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
elsif addr.ip_address == "0.0.0.0" # MacOS X 10.4 returns "a.b.c.d" for IPv4-mapped IPv6 address.
addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
elsif addr.ip_address == "::ffff:0.0.0.0" # MacOS X 10.6 returns "::ffff:a.b.c.d" for IPv4-mapped IPv6 address.
addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
end
elsif defined?(Socket::AF_UNIX) && afamily == Socket::AF_UNIX
raise SocketError, "unbound Unix socket" if addr.unix_path == ""
end
addr
end
end
class Socket < BasicSocket
# enable the socket option IPV6_V6ONLY if IPV6_V6ONLY is available.
def ipv6only!
if defined? Socket::IPV6_V6ONLY
self.setsockopt(:IPV6, :V6ONLY, 1)
end
end
# creates a new socket object connected to host:port using TCP/IP.
#
# If local_host:local_port is given,
# the socket is bound to it.
#
# 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.
#
# 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
# }
#
def self.tcp(host, port, local_host=nil, local_port=nil) # :yield: socket
last_error = nil
ret = nil
local_addr_list = nil
if local_host != nil || local_port != nil
local_addr_list = Addrinfo.getaddrinfo(local_host, local_port, nil, :STREAM, nil)
end
Addrinfo.foreach(host, port, nil, :STREAM) {|ai|
if local_addr_list
local_addr = local_addr_list.find {|local_ai| local_ai.afamily == ai.afamily }
next if !local_addr
else
local_addr = nil
end
begin
sock = local_addr ? ai.connect_from(local_addr) : ai.connect
rescue SystemCallError
last_error = $!
next
end
ret = sock
break
}
if !ret
if last_error
raise last_error
else
raise SocketError, "no appropriate local address"
end
end
if block_given?
begin
yield ret
ensure
ret.close if !ret.closed?
end
else
ret
end
end
# :stopdoc:
def self.ip_sockets_port0(ai_list, reuseaddr)
sockets = []
begin
sockets.clear
port = nil
ai_list.each {|ai|
begin
s = Socket.new(ai.pfamily, ai.socktype, ai.protocol)
rescue SystemCallError
next
end
sockets << s
s.ipv6only! if ai.ipv6?
if reuseaddr
s.setsockopt(:SOCKET, :REUSEADDR, 1)
end
if !port
s.bind(ai)
port = s.local_address.ip_port
else
s.bind(ai.family_addrinfo(ai.ip_address, port))
end
}
rescue Errno::EADDRINUSE
sockets.each {|s| s.close }
retry
rescue Exception
sockets.each {|s| s.close }
raise
end
sockets
end
class << self
private :ip_sockets_port0
end
def self.tcp_server_sockets_port0(host)
ai_list = Addrinfo.getaddrinfo(host, 0, nil, :STREAM, nil, Socket::AI_PASSIVE)
sockets = ip_sockets_port0(ai_list, true)
begin
sockets.each {|s|
s.listen(5)
}
rescue Exception
sockets.each {|s| s.close }
raise
end
sockets
end
class << self
private :tcp_server_sockets_port0
Loading ...