Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
IPSocket#addr
(?::boolish | :hostname | :numeric reverse_lookup) -> [ ::String, ::Integer, ::String, ::String ]
ipsocket.addr([reverse_lookup]) => [address_family, port, hostname, numeric_address]
ext/socket/ipsocket.c
View on GitHub ↗
static VALUE
ip_addr(int argc, VALUE *argv, VALUE sock)
{
union_sockaddr addr;
socklen_t len = (socklen_t)sizeof addr;
int norevlookup;
if (argc < 1 || !rsock_revlookup_flag(argv[0], &norevlookup))
norevlookup = rb_io_mode(sock) & FMODE_NOREVLOOKUP;
if (getsockname(rb_io_descriptor(sock), &addr.addr, &len) < 0)
rb_sys_fail("getsockname(2)");
return rsock_ipaddr(&addr.addr, len, norevlookup);
}
Returns the local address as an array which contains address_family, port, hostname and numeric_address.
If reverse_lookup is true or :hostname, hostname is obtained from numeric_address using reverse lookup. Or if it is false, or :numeric, hostname is the same as numeric_address. Or if it is nil or omitted, obeys to ipsocket.do_not_reverse_lookup. See Socket.getaddrinfo also.
Example
TCPSocket.open("www.ruby-lang.org", 80) {|sock| p sock.addr #=> ["AF_INET", 49429, "hal", "192.168.0.128"] p sock.addr(true) #=> ["AF_INET", 49429, "hal", "192.168.0.128"] p sock.addr(false) #=> ["AF_INET", 49429, "192.168.0.128", "192.168.0.128"] p sock.addr(:hostname) #=> ["AF_INET", 49429, "hal", "192.168.0.128"] p sock.addr(:numeric) #=> ["AF_INET", 49429, "192.168.0.128", "192.168.0.128"] }