Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
class method
Socket.gethostname
() -> ::String
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;
}
char *s = RSTRING_PTR(name), *p = memchr(s, 0, len);
if (p) rb_str_resize(name, (long)(p - s));
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
.getaddrinfo
.getifaddrs
.accept_loop
.getnameinfo
also in
4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0