Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
BasicSocket#getsockopt
static VALUE
bsock_getsockopt(VALUE sock, VALUE lev, VALUE optname)
{
int level, option;
socklen_t len;
char *buf;
rb_io_t *fptr;
int family;
GetOpenFile(sock, fptr);
family = rsock_getfamily(fptr);
level = rsock_level_arg(family, lev);
option = rsock_optname_arg(family, level, optname);
len = 256;
#ifdef _AIX
switch (option) {
case SO_DEBUG:
case SO_REUSEADDR:
case SO_KEEPALIVE:
case SO_DONTROUTE:
case SO_BROADCAST:
case SO_OOBINLINE:
/* AIX doesn't set len for boolean options */
len = sizeof(int);
}
#endif
buf = ALLOCA_N(char,len);
rb_io_check_closed(fptr);
if (getsockopt(fptr->fd, level, option, buf, &len) < 0)
rsock_sys_fail_path("getsockopt(2)", fptr->pathv);
return rsock_sockopt_new(family, level, option, rb_str_new(buf, len));
}
Gets a socket option. These are protocol and system specific, see your local system documentation for details. The option is returned as a Socket::Option object.
Parameters
-
levelis an integer, usually one of the SOL_ constants such asSocket::SOL_SOCKET, or a protocol level. A string or symbol of the name, possibly without prefix, is also accepted. -
optnameis an integer, usually one of the SO_ constants, such asSocket::SO_REUSEADDR. A string or symbol of the name, possibly without prefix, is also accepted.
Examples
Some socket options are integers with boolean values, in this case getsockopt could be called like this:
reuseaddr = sock.getsockopt(:SOCKET, :REUSEADDR).bool optval = sock.getsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR) optval = optval.unpack "i" reuseaddr = optval[0] == 0 ? false : true
Some socket options are integers with numeric values, in this case getsockopt could be called like this:
ipttl = sock.getsockopt(:IP, :TTL).int optval = sock.getsockopt(Socket::IPPROTO_IP, Socket::IP_TTL) ipttl = optval.unpack1("i")
Option values may be structs. Decoding them can be complex as it involves examining your system headers to determine the correct definition. An example is a +struct linger+, which may be defined in your system headers as:
struct linger { int l_onoff; int l_linger; };
In this case getsockopt could be called like this:
# Socket::Option knows linger structure. onoff, linger = sock.getsockopt(:SOCKET, :LINGER).linger optval = sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER) onoff, linger = optval.unpack "ii" onoff = onoff == 0 ? false : true