Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
class method
Socket.gethostname
Socket.gethostname => hostname
ext/socket/socket.c
View on GitHub ↗
static VALUE
sock_gethostname(VALUE obj)
{
#if defined(NI_MAXHOST)
# define RUBY_MAX_HOST_NAME_LEN NI_MAXHOST
#elif defined(HOST_NAME_MAX)
# define RUBY_MAX_HOST_NAME_LEN HOST_NAME_MAX
#else
# define RUBY_MAX_HOST_NAME_LEN 1024
#endif
long len = RUBY_MAX_HOST_NAME_LEN;
VALUE name;
name = rb_str_new(0, len);
while (gethostname(RSTRING_PTR(name), len) < 0) {
int e = errno;
switch (e) {
case ENAMETOOLONG:
#ifdef __linux__
case EINVAL:
/* glibc before version 2.1 uses EINVAL instead of ENAMETOOLONG */
#endif
break;
default:
rb_syserr_fail(e, "gethostname(3)");
}
rb_str_modify_expand(name, len);
len += len;
}
rb_str_resize(name, strlen(RSTRING_PTR(name)));
return name;
}
Returns the hostname.
Example
p Socket.gethostname #=> "hal"
Note that it is not guaranteed to be able to convert to IP address using gethostbyname, getaddrinfo, etc. If you need local IP address, use Socket.ip_address_list.
See also
.gethostbyname
.getifaddrs
.gethostbyaddr
.getnameinfo
also in
4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0