Ruby 2.7.6p219 (2022-04-12 revision c9c2245c0a25176072e02db9254f0e0c84c805cd)
socket.c
Go to the documentation of this file.
1/************************************************
2
3 socket.c -
4
5 created at: Thu Mar 31 12:21:29 JST 1994
6
7 Copyright (C) 1993-2007 Yukihiro Matsumoto
8
9************************************************/
10
11#include "rubysocket.h"
12
13static VALUE sym_wait_writable;
14
15static VALUE sock_s_unpack_sockaddr_in(VALUE, VALUE);
16
17void
18rsock_sys_fail_host_port(const char *mesg, VALUE host, VALUE port)
19{
20 rsock_syserr_fail_host_port(errno, mesg, host, port);
21}
22
23void
24rsock_syserr_fail_host_port(int err, const char *mesg, VALUE host, VALUE port)
25{
26 VALUE message;
27
28 message = rb_sprintf("%s for %+"PRIsVALUE" port % "PRIsVALUE"",
29 mesg, host, port);
30
31 rb_syserr_fail_str(err, message);
32}
33
34void
35rsock_sys_fail_path(const char *mesg, VALUE path)
36{
38}
39
40void
41rsock_syserr_fail_path(int err, const char *mesg, VALUE path)
42{
43 VALUE message;
44
45 if (RB_TYPE_P(path, T_STRING)) {
46 message = rb_sprintf("%s for % "PRIsVALUE"", mesg, path);
47 rb_syserr_fail_str(err, message);
48 }
49 else {
50 rb_syserr_fail(err, mesg);
51 }
52}
53
54void
55rsock_sys_fail_sockaddr(const char *mesg, struct sockaddr *addr, socklen_t len)
56{
58}
59
60void
61rsock_syserr_fail_sockaddr(int err, const char *mesg, struct sockaddr *addr, socklen_t len)
62{
63 VALUE rai;
64
65 rai = rsock_addrinfo_new(addr, len, PF_UNSPEC, 0, 0, Qnil, Qnil);
66
68}
69
70void
71rsock_sys_fail_raddrinfo(const char *mesg, VALUE rai)
72{
74}
75
76void
77rsock_syserr_fail_raddrinfo(int err, const char *mesg, VALUE rai)
78{
79 VALUE str, message;
80
82 message = rb_sprintf("%s for %"PRIsVALUE"", mesg, str);
83
84 rb_syserr_fail_str(err, message);
85}
86
87void
89{
91}
92
93void
94rsock_syserr_fail_raddrinfo_or_sockaddr(int err, const char *mesg, VALUE addr, VALUE rai)
95{
96 if (NIL_P(rai)) {
97 StringValue(addr);
98
100 (struct sockaddr *)RSTRING_PTR(addr),
101 (socklen_t)RSTRING_LEN(addr)); /* overflow should be checked already */
102 }
103 else
105}
106
107static void
108setup_domain_and_type(VALUE domain, int *dv, VALUE type, int *tv)
109{
110 *dv = rsock_family_arg(domain);
112}
113
114/*
115 * call-seq:
116 * Socket.new(domain, socktype [, protocol]) => socket
117 *
118 * Creates a new socket object.
119 *
120 * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc.
121 *
122 * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
123 *
124 * _protocol_ is optional and should be a protocol defined in the domain.
125 * If protocol is not given, 0 is used internally.
126 *
127 * Socket.new(:INET, :STREAM) # TCP socket
128 * Socket.new(:INET, :DGRAM) # UDP socket
129 * Socket.new(:UNIX, :STREAM) # UNIX stream socket
130 * Socket.new(:UNIX, :DGRAM) # UNIX datagram socket
131 */
132static VALUE
133sock_initialize(int argc, VALUE *argv, VALUE sock)
134{
135 VALUE domain, type, protocol;
136 int fd;
137 int d, t;
138
139 rb_scan_args(argc, argv, "21", &domain, &type, &protocol);
140 if (NIL_P(protocol))
141 protocol = INT2FIX(0);
142
143 setup_domain_and_type(domain, &d, type, &t);
144 fd = rsock_socket(d, t, NUM2INT(protocol));
145 if (fd < 0) rb_sys_fail("socket(2)");
146
147 return rsock_init_sock(sock, fd);
148}
149
150#if defined HAVE_SOCKETPAIR
151static VALUE
152io_call_close(VALUE io)
153{
154 return rb_funcallv(io, rb_intern("close"), 0, 0);
155}
156
157static VALUE
158io_close(VALUE io)
159{
160 return rb_rescue(io_call_close, io, 0, 0);
161}
162
163static VALUE
164pair_yield(VALUE pair)
165{
166 return rb_ensure(rb_yield, pair, io_close, rb_ary_entry(pair, 1));
167}
168#endif
169
170#if defined HAVE_SOCKETPAIR
171
172#ifdef SOCK_CLOEXEC
173static int
174rsock_socketpair0(int domain, int type, int protocol, int sv[2])
175{
176 int ret;
177 static int cloexec_state = -1; /* <0: unknown, 0: ignored, >0: working */
178 static const int default_flags = SOCK_CLOEXEC|RSOCK_NONBLOCK_DEFAULT;
179
180 if (cloexec_state > 0) { /* common path, if SOCK_CLOEXEC is defined */
181 ret = socketpair(domain, type|default_flags, protocol, sv);
182 if (ret == 0 && (sv[0] <= 2 || sv[1] <= 2)) {
183 goto fix_cloexec; /* highly unlikely */
184 }
185 goto update_max_fd;
186 }
187 else if (cloexec_state < 0) { /* usually runs once only for detection */
188 ret = socketpair(domain, type|default_flags, protocol, sv);
189 if (ret == 0) {
190 cloexec_state = rsock_detect_cloexec(sv[0]);
191 if ((cloexec_state == 0) || (sv[0] <= 2 || sv[1] <= 2))
192 goto fix_cloexec;
193 goto update_max_fd;
194 }
195 else if (ret == -1 && errno == EINVAL) {
196 /* SOCK_CLOEXEC is available since Linux 2.6.27. Linux 2.6.18 fails with EINVAL */
197 ret = socketpair(domain, type, protocol, sv);
198 if (ret != -1) {
199 /* The reason of EINVAL may be other than SOCK_CLOEXEC.
200 * So disable SOCK_CLOEXEC only if socketpair() succeeds without SOCK_CLOEXEC.
201 * Ex. Socket.pair(:UNIX, 0xff) fails with EINVAL.
202 */
203 cloexec_state = 0;
204 }
205 }
206 }
207 else { /* cloexec_state == 0 */
208 ret = socketpair(domain, type, protocol, sv);
209 }
210 if (ret == -1) {
211 return -1;
212 }
213
214fix_cloexec:
220 }
221
222update_max_fd:
223 rb_update_max_fd(sv[0]);
224 rb_update_max_fd(sv[1]);
225
226 return ret;
227}
228#else /* !SOCK_CLOEXEC */
229static int
230rsock_socketpair0(int domain, int type, int protocol, int sv[2])
231{
232 int ret = socketpair(domain, type, protocol, sv);
233
234 if (ret == -1)
235 return -1;
236
237 rb_fd_fix_cloexec(sv[0]);
238 rb_fd_fix_cloexec(sv[1]);
242 }
243 return ret;
244}
245#endif /* !SOCK_CLOEXEC */
246
247static int
248rsock_socketpair(int domain, int type, int protocol, int sv[2])
249{
250 int ret;
251
252 ret = rsock_socketpair0(domain, type, protocol, sv);
253 if (ret < 0 && rb_gc_for_fd(errno)) {
254 ret = rsock_socketpair0(domain, type, protocol, sv);
255 }
256
257 return ret;
258}
259
260/*
261 * call-seq:
262 * Socket.pair(domain, type, protocol) => [socket1, socket2]
263 * Socket.socketpair(domain, type, protocol) => [socket1, socket2]
264 *
265 * Creates a pair of sockets connected each other.
266 *
267 * _domain_ should be a communications domain such as: :INET, :INET6, :UNIX, etc.
268 *
269 * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
270 *
271 * _protocol_ should be a protocol defined in the domain,
272 * defaults to 0 for the domain.
273 *
274 * s1, s2 = Socket.pair(:UNIX, :STREAM, 0)
275 * s1.send "a", 0
276 * s1.send "b", 0
277 * s1.close
278 * p s2.recv(10) #=> "ab"
279 * p s2.recv(10) #=> ""
280 * p s2.recv(10) #=> ""
281 *
282 * s1, s2 = Socket.pair(:UNIX, :DGRAM, 0)
283 * s1.send "a", 0
284 * s1.send "b", 0
285 * p s2.recv(10) #=> "a"
286 * p s2.recv(10) #=> "b"
287 *
288 */
289VALUE
291{
292 VALUE domain, type, protocol;
293 int d, t, p, sp[2];
294 int ret;
295 VALUE s1, s2, r;
296
297 rb_scan_args(argc, argv, "21", &domain, &type, &protocol);
298 if (NIL_P(protocol))
299 protocol = INT2FIX(0);
300
301 setup_domain_and_type(domain, &d, type, &t);
302 p = NUM2INT(protocol);
303 ret = rsock_socketpair(d, t, p, sp);
304 if (ret < 0) {
305 rb_sys_fail("socketpair(2)");
306 }
307
308 s1 = rsock_init_sock(rb_obj_alloc(klass), sp[0]);
310 r = rb_assoc_new(s1, s2);
311 if (rb_block_given_p()) {
312 return rb_ensure(pair_yield, r, io_close, s1);
313 }
314 return r;
315}
316#else
317#define rsock_sock_s_socketpair rb_f_notimplement
318#endif
319
320/*
321 * call-seq:
322 * socket.connect(remote_sockaddr) => 0
323 *
324 * Requests a connection to be made on the given +remote_sockaddr+. Returns 0 if
325 * successful, otherwise an exception is raised.
326 *
327 * === Parameter
328 * * +remote_sockaddr+ - the +struct+ sockaddr contained in a string or Addrinfo object
329 *
330 * === Example:
331 * # Pull down Google's web page
332 * require 'socket'
333 * include Socket::Constants
334 * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
335 * sockaddr = Socket.pack_sockaddr_in( 80, 'www.google.com' )
336 * socket.connect( sockaddr )
337 * socket.write( "GET / HTTP/1.0\r\n\r\n" )
338 * results = socket.read
339 *
340 * === Unix-based Exceptions
341 * On unix-based systems the following system exceptions may be raised if
342 * the call to _connect_ fails:
343 * * Errno::EACCES - search permission is denied for a component of the prefix
344 * path or write access to the +socket+ is denied
345 * * Errno::EADDRINUSE - the _sockaddr_ is already in use
346 * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
347 * local machine
348 * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for
349 * the address family of the specified +socket+
350 * * Errno::EALREADY - a connection is already in progress for the specified
351 * socket
352 * * Errno::EBADF - the +socket+ is not a valid file descriptor
353 * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
354 * refused the connection request
355 * * Errno::ECONNRESET - the remote host reset the connection request
356 * * Errno::EFAULT - the _sockaddr_ cannot be accessed
357 * * Errno::EHOSTUNREACH - the destination host cannot be reached (probably
358 * because the host is down or a remote router cannot reach it)
359 * * Errno::EINPROGRESS - the O_NONBLOCK is set for the +socket+ and the
360 * connection cannot be immediately established; the connection will be
361 * established asynchronously
362 * * Errno::EINTR - the attempt to establish the connection was interrupted by
363 * delivery of a signal that was caught; the connection will be established
364 * asynchronously
365 * * Errno::EISCONN - the specified +socket+ is already connected
366 * * Errno::EINVAL - the address length used for the _sockaddr_ is not a valid
367 * length for the address family or there is an invalid family in _sockaddr_
368 * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
369 * PATH_MAX
370 * * Errno::ENETDOWN - the local interface used to reach the destination is down
371 * * Errno::ENETUNREACH - no route to the network is present
372 * * Errno::ENOBUFS - no buffer space is available
373 * * Errno::ENOSR - there were insufficient STREAMS resources available to
374 * complete the operation
375 * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
376 * * Errno::EOPNOTSUPP - the calling +socket+ is listening and cannot be connected
377 * * Errno::EPROTOTYPE - the _sockaddr_ has a different type than the socket
378 * bound to the specified peer address
379 * * Errno::ETIMEDOUT - the attempt to connect time out before a connection
380 * was made.
381 *
382 * On unix-based systems if the address family of the calling +socket+ is
383 * AF_UNIX the follow exceptions may be raised if the call to _connect_
384 * fails:
385 * * Errno::EIO - an i/o error occurred while reading from or writing to the
386 * file system
387 * * Errno::ELOOP - too many symbolic links were encountered in translating
388 * the pathname in _sockaddr_
389 * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
390 * characters, or an entire pathname exceeded PATH_MAX characters
391 * * Errno::ENOENT - a component of the pathname does not name an existing file
392 * or the pathname is an empty string
393 * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
394 * is not a directory
395 *
396 * === Windows Exceptions
397 * On Windows systems the following system exceptions may be raised if
398 * the call to _connect_ fails:
399 * * Errno::ENETDOWN - the network is down
400 * * Errno::EADDRINUSE - the socket's local address is already in use
401 * * Errno::EINTR - the socket was cancelled
402 * * Errno::EINPROGRESS - a blocking socket is in progress or the service provider
403 * is still processing a callback function. Or a nonblocking connect call is
404 * in progress on the +socket+.
405 * * Errno::EALREADY - see Errno::EINVAL
406 * * Errno::EADDRNOTAVAIL - the remote address is not a valid address, such as
407 * ADDR_ANY TODO check ADDRANY TO INADDR_ANY
408 * * Errno::EAFNOSUPPORT - addresses in the specified family cannot be used with
409 * with this +socket+
410 * * Errno::ECONNREFUSED - the target _sockaddr_ was not listening for connections
411 * refused the connection request
412 * * Errno::EFAULT - the socket's internal address or address length parameter
413 * is too small or is not a valid part of the user space address
414 * * Errno::EINVAL - the +socket+ is a listening socket
415 * * Errno::EISCONN - the +socket+ is already connected
416 * * Errno::ENETUNREACH - the network cannot be reached from this host at this time
417 * * Errno::EHOSTUNREACH - no route to the network is present
418 * * Errno::ENOBUFS - no buffer space is available
419 * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
420 * * Errno::ETIMEDOUT - the attempt to connect time out before a connection
421 * was made.
422 * * Errno::EWOULDBLOCK - the socket is marked as nonblocking and the
423 * connection cannot be completed immediately
424 * * Errno::EACCES - the attempt to connect the datagram socket to the
425 * broadcast address failed
426 *
427 * === See
428 * * connect manual pages on unix-based systems
429 * * connect function in Microsoft's Winsock functions reference
430 */
431static VALUE
432sock_connect(VALUE sock, VALUE addr)
433{
434 VALUE rai;
435 rb_io_t *fptr;
436 int fd, n;
437
439 addr = rb_str_new4(addr);
440 GetOpenFile(sock, fptr);
441 fd = fptr->fd;
442 n = rsock_connect(fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr), 0);
443 if (n < 0) {
444 rsock_sys_fail_raddrinfo_or_sockaddr("connect(2)", addr, rai);
445 }
446
447 return INT2FIX(n);
448}
449
450/* :nodoc: */
451static VALUE
452sock_connect_nonblock(VALUE sock, VALUE addr, VALUE ex)
453{
454 VALUE rai;
455 rb_io_t *fptr;
456 int n;
457
459 addr = rb_str_new4(addr);
460 GetOpenFile(sock, fptr);
461 rb_io_set_nonblock(fptr);
462 n = connect(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr));
463 if (n < 0) {
464 int e = errno;
465 if (e == EINPROGRESS) {
466 if (ex == Qfalse) {
467 return sym_wait_writable;
468 }
469 rb_readwrite_syserr_fail(RB_IO_WAIT_WRITABLE, e, "connect(2) would block");
470 }
471 if (e == EISCONN) {
472 if (ex == Qfalse) {
473 return INT2FIX(0);
474 }
475 }
476 rsock_syserr_fail_raddrinfo_or_sockaddr(e, "connect(2)", addr, rai);
477 }
478
479 return INT2FIX(n);
480}
481
482/*
483 * call-seq:
484 * socket.bind(local_sockaddr) => 0
485 *
486 * Binds to the given local address.
487 *
488 * === Parameter
489 * * +local_sockaddr+ - the +struct+ sockaddr contained in a string or an Addrinfo object
490 *
491 * === Example
492 * require 'socket'
493 *
494 * # use Addrinfo
495 * socket = Socket.new(:INET, :STREAM, 0)
496 * socket.bind(Addrinfo.tcp("127.0.0.1", 2222))
497 * p socket.local_address #=> #<Addrinfo: 127.0.0.1:2222 TCP>
498 *
499 * # use struct sockaddr
500 * include Socket::Constants
501 * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
502 * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
503 * socket.bind( sockaddr )
504 *
505 * === Unix-based Exceptions
506 * On unix-based based systems the following system exceptions may be raised if
507 * the call to _bind_ fails:
508 * * Errno::EACCES - the specified _sockaddr_ is protected and the current
509 * user does not have permission to bind to it
510 * * Errno::EADDRINUSE - the specified _sockaddr_ is already in use
511 * * Errno::EADDRNOTAVAIL - the specified _sockaddr_ is not available from the
512 * local machine
513 * * Errno::EAFNOSUPPORT - the specified _sockaddr_ is not a valid address for
514 * the family of the calling +socket+
515 * * Errno::EBADF - the _sockaddr_ specified is not a valid file descriptor
516 * * Errno::EFAULT - the _sockaddr_ argument cannot be accessed
517 * * Errno::EINVAL - the +socket+ is already bound to an address, and the
518 * protocol does not support binding to the new _sockaddr_ or the +socket+
519 * has been shut down.
520 * * Errno::EINVAL - the address length is not a valid length for the address
521 * family
522 * * Errno::ENAMETOOLONG - the pathname resolved had a length which exceeded
523 * PATH_MAX
524 * * Errno::ENOBUFS - no buffer space is available
525 * * Errno::ENOSR - there were insufficient STREAMS resources available to
526 * complete the operation
527 * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
528 * * Errno::EOPNOTSUPP - the socket type of the +socket+ does not support
529 * binding to an address
530 *
531 * On unix-based based systems if the address family of the calling +socket+ is
532 * Socket::AF_UNIX the follow exceptions may be raised if the call to _bind_
533 * fails:
534 * * Errno::EACCES - search permission is denied for a component of the prefix
535 * path or write access to the +socket+ is denied
536 * * Errno::EDESTADDRREQ - the _sockaddr_ argument is a null pointer
537 * * Errno::EISDIR - same as Errno::EDESTADDRREQ
538 * * Errno::EIO - an i/o error occurred
539 * * Errno::ELOOP - too many symbolic links were encountered in translating
540 * the pathname in _sockaddr_
541 * * Errno::ENAMETOOLLONG - a component of a pathname exceeded NAME_MAX
542 * characters, or an entire pathname exceeded PATH_MAX characters
543 * * Errno::ENOENT - a component of the pathname does not name an existing file
544 * or the pathname is an empty string
545 * * Errno::ENOTDIR - a component of the path prefix of the pathname in _sockaddr_
546 * is not a directory
547 * * Errno::EROFS - the name would reside on a read only filesystem
548 *
549 * === Windows Exceptions
550 * On Windows systems the following system exceptions may be raised if
551 * the call to _bind_ fails:
552 * * Errno::ENETDOWN-- the network is down
553 * * Errno::EACCES - the attempt to connect the datagram socket to the
554 * broadcast address failed
555 * * Errno::EADDRINUSE - the socket's local address is already in use
556 * * Errno::EADDRNOTAVAIL - the specified address is not a valid address for this
557 * computer
558 * * Errno::EFAULT - the socket's internal address or address length parameter
559 * is too small or is not a valid part of the user space addressed
560 * * Errno::EINVAL - the +socket+ is already bound to an address
561 * * Errno::ENOBUFS - no buffer space is available
562 * * Errno::ENOTSOCK - the +socket+ argument does not refer to a socket
563 *
564 * === See
565 * * bind manual pages on unix-based systems
566 * * bind function in Microsoft's Winsock functions reference
567 */
568static VALUE
569sock_bind(VALUE sock, VALUE addr)
570{
571 VALUE rai;
572 rb_io_t *fptr;
573
575 GetOpenFile(sock, fptr);
576 if (bind(fptr->fd, (struct sockaddr*)RSTRING_PTR(addr), RSTRING_SOCKLEN(addr)) < 0)
577 rsock_sys_fail_raddrinfo_or_sockaddr("bind(2)", addr, rai);
578
579 return INT2FIX(0);
580}
581
582/*
583 * call-seq:
584 * socket.listen( int ) => 0
585 *
586 * Listens for connections, using the specified +int+ as the backlog. A call
587 * to _listen_ only applies if the +socket+ is of type SOCK_STREAM or
588 * SOCK_SEQPACKET.
589 *
590 * === Parameter
591 * * +backlog+ - the maximum length of the queue for pending connections.
592 *
593 * === Example 1
594 * require 'socket'
595 * include Socket::Constants
596 * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
597 * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
598 * socket.bind( sockaddr )
599 * socket.listen( 5 )
600 *
601 * === Example 2 (listening on an arbitrary port, unix-based systems only):
602 * require 'socket'
603 * include Socket::Constants
604 * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
605 * socket.listen( 1 )
606 *
607 * === Unix-based Exceptions
608 * On unix based systems the above will work because a new +sockaddr+ struct
609 * is created on the address ADDR_ANY, for an arbitrary port number as handed
610 * off by the kernel. It will not work on Windows, because Windows requires that
611 * the +socket+ is bound by calling _bind_ before it can _listen_.
612 *
613 * If the _backlog_ amount exceeds the implementation-dependent maximum
614 * queue length, the implementation's maximum queue length will be used.
615 *
616 * On unix-based based systems the following system exceptions may be raised if the
617 * call to _listen_ fails:
618 * * Errno::EBADF - the _socket_ argument is not a valid file descriptor
619 * * Errno::EDESTADDRREQ - the _socket_ is not bound to a local address, and
620 * the protocol does not support listening on an unbound socket
621 * * Errno::EINVAL - the _socket_ is already connected
622 * * Errno::ENOTSOCK - the _socket_ argument does not refer to a socket
623 * * Errno::EOPNOTSUPP - the _socket_ protocol does not support listen
624 * * Errno::EACCES - the calling process does not have appropriate privileges
625 * * Errno::EINVAL - the _socket_ has been shut down
626 * * Errno::ENOBUFS - insufficient resources are available in the system to
627 * complete the call
628 *
629 * === Windows Exceptions
630 * On Windows systems the following system exceptions may be raised if
631 * the call to _listen_ fails:
632 * * Errno::ENETDOWN - the network is down
633 * * Errno::EADDRINUSE - the socket's local address is already in use. This
634 * usually occurs during the execution of _bind_ but could be delayed
635 * if the call to _bind_ was to a partially wildcard address (involving
636 * ADDR_ANY) and if a specific address needs to be committed at the
637 * time of the call to _listen_
638 * * Errno::EINPROGRESS - a Windows Sockets 1.1 call is in progress or the
639 * service provider is still processing a callback function
640 * * Errno::EINVAL - the +socket+ has not been bound with a call to _bind_.
641 * * Errno::EISCONN - the +socket+ is already connected
642 * * Errno::EMFILE - no more socket descriptors are available
643 * * Errno::ENOBUFS - no buffer space is available
644 * * Errno::ENOTSOC - +socket+ is not a socket
645 * * Errno::EOPNOTSUPP - the referenced +socket+ is not a type that supports
646 * the _listen_ method
647 *
648 * === See
649 * * listen manual pages on unix-based systems
650 * * listen function in Microsoft's Winsock functions reference
651 */
652VALUE
654{
655 rb_io_t *fptr;
656 int backlog;
657
658 backlog = NUM2INT(log);
659 GetOpenFile(sock, fptr);
660 if (listen(fptr->fd, backlog) < 0)
661 rb_sys_fail("listen(2)");
662
663 return INT2FIX(0);
664}
665
666/*
667 * call-seq:
668 * socket.recvfrom(maxlen) => [mesg, sender_addrinfo]
669 * socket.recvfrom(maxlen, flags) => [mesg, sender_addrinfo]
670 *
671 * Receives up to _maxlen_ bytes from +socket+. _flags_ is zero or more
672 * of the +MSG_+ options. The first element of the results, _mesg_, is the data
673 * received. The second element, _sender_addrinfo_, contains protocol-specific
674 * address information of the sender.
675 *
676 * === Parameters
677 * * +maxlen+ - the maximum number of bytes to receive from the socket
678 * * +flags+ - zero or more of the +MSG_+ options
679 *
680 * === Example
681 * # In one file, start this first
682 * require 'socket'
683 * include Socket::Constants
684 * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
685 * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
686 * socket.bind( sockaddr )
687 * socket.listen( 5 )
688 * client, client_addrinfo = socket.accept
689 * data = client.recvfrom( 20 )[0].chomp
690 * puts "I only received 20 bytes '#{data}'"
691 * sleep 1
692 * socket.close
693 *
694 * # In another file, start this second
695 * require 'socket'
696 * include Socket::Constants
697 * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
698 * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
699 * socket.connect( sockaddr )
700 * socket.puts "Watch this get cut short!"
701 * socket.close
702 *
703 * === Unix-based Exceptions
704 * On unix-based based systems the following system exceptions may be raised if the
705 * call to _recvfrom_ fails:
706 * * Errno::EAGAIN - the +socket+ file descriptor is marked as O_NONBLOCK and no
707 * data is waiting to be received; or MSG_OOB is set and no out-of-band data
708 * is available and either the +socket+ file descriptor is marked as
709 * O_NONBLOCK or the +socket+ does not support blocking to wait for
710 * out-of-band-data
711 * * Errno::EWOULDBLOCK - see Errno::EAGAIN
712 * * Errno::EBADF - the +socket+ is not a valid file descriptor
713 * * Errno::ECONNRESET - a connection was forcibly closed by a peer
714 * * Errno::EFAULT - the socket's internal buffer, address or address length
715 * cannot be accessed or written
716 * * Errno::EINTR - a signal interrupted _recvfrom_ before any data was available
717 * * Errno::EINVAL - the MSG_OOB flag is set and no out-of-band data is available
718 * * Errno::EIO - an i/o error occurred while reading from or writing to the
719 * filesystem
720 * * Errno::ENOBUFS - insufficient resources were available in the system to
721 * perform the operation
722 * * Errno::ENOMEM - insufficient memory was available to fulfill the request
723 * * Errno::ENOSR - there were insufficient STREAMS resources available to
724 * complete the operation
725 * * Errno::ENOTCONN - a receive is attempted on a connection-mode socket that
726 * is not connected
727 * * Errno::ENOTSOCK - the +socket+ does not refer to a socket
728 * * Errno::EOPNOTSUPP - the specified flags are not supported for this socket type
729 * * Errno::ETIMEDOUT - the connection timed out during connection establishment
730 * or due to a transmission timeout on an active connection
731 *
732 * === Windows Exceptions
733 * On Windows systems the following system exceptions may be raised if
734 * the call to _recvfrom_ fails:
735 * * Errno::ENETDOWN - the network is down
736 * * Errno::EFAULT - the internal buffer and from parameters on +socket+ are not
737 * part of the user address space, or the internal fromlen parameter is
738 * too small to accommodate the peer address
739 * * Errno::EINTR - the (blocking) call was cancelled by an internal call to
740 * the WinSock function WSACancelBlockingCall
741 * * Errno::EINPROGRESS - a blocking Windows Sockets 1.1 call is in progress or
742 * the service provider is still processing a callback function
743 * * Errno::EINVAL - +socket+ has not been bound with a call to _bind_, or an
744 * unknown flag was specified, or MSG_OOB was specified for a socket with
745 * SO_OOBINLINE enabled, or (for byte stream-style sockets only) the internal
746 * len parameter on +socket+ was zero or negative
747 * * Errno::EISCONN - +socket+ is already connected. The call to _recvfrom_ is
748 * not permitted with a connected socket on a socket that is connection
749 * oriented or connectionless.
750 * * Errno::ENETRESET - the connection has been broken due to the keep-alive
751 * activity detecting a failure while the operation was in progress.
752 * * Errno::EOPNOTSUPP - MSG_OOB was specified, but +socket+ is not stream-style
753 * such as type SOCK_STREAM. OOB data is not supported in the communication
754 * domain associated with +socket+, or +socket+ is unidirectional and
755 * supports only send operations
756 * * Errno::ESHUTDOWN - +socket+ has been shutdown. It is not possible to
757 * call _recvfrom_ on a socket after _shutdown_ has been invoked.
758 * * Errno::EWOULDBLOCK - +socket+ is marked as nonblocking and a call to
759 * _recvfrom_ would block.
760 * * Errno::EMSGSIZE - the message was too large to fit into the specified buffer
761 * and was truncated.
762 * * Errno::ETIMEDOUT - the connection has been dropped, because of a network
763 * failure or because the system on the other end went down without
764 * notice
765 * * Errno::ECONNRESET - the virtual circuit was reset by the remote side
766 * executing a hard or abortive close. The application should close the
767 * socket; it is no longer usable. On a UDP-datagram socket this error
768 * indicates a previous send operation resulted in an ICMP Port Unreachable
769 * message.
770 */
771static VALUE
772sock_recvfrom(int argc, VALUE *argv, VALUE sock)
773{
774 return rsock_s_recvfrom(sock, argc, argv, RECV_SOCKET);
775}
776
777/* :nodoc: */
778static VALUE
779sock_recvfrom_nonblock(VALUE sock, VALUE len, VALUE flg, VALUE str, VALUE ex)
780{
781 return rsock_s_recvfrom_nonblock(sock, len, flg, str, ex, RECV_SOCKET);
782}
783
784/*
785 * call-seq:
786 * socket.accept => [client_socket, client_addrinfo]
787 *
788 * Accepts a next connection.
789 * Returns a new Socket object and Addrinfo object.
790 *
791 * serv = Socket.new(:INET, :STREAM, 0)
792 * serv.listen(5)
793 * c = Socket.new(:INET, :STREAM, 0)
794 * c.connect(serv.connect_address)
795 * p serv.accept #=> [#<Socket:fd 6>, #<Addrinfo: 127.0.0.1:48555 TCP>]
796 *
797 */
798static VALUE
799sock_accept(VALUE sock)
800{
801 rb_io_t *fptr;
802 VALUE sock2;
804 socklen_t len = (socklen_t)sizeof buf;
805
806 GetOpenFile(sock, fptr);
807 sock2 = rsock_s_accept(rb_cSocket,fptr->fd,&buf.addr,&len);
808
809 return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, &buf.addr, len));
810}
811
812/* :nodoc: */
813static VALUE
814sock_accept_nonblock(VALUE sock, VALUE ex)
815{
816 rb_io_t *fptr;
817 VALUE sock2;
819 struct sockaddr *addr = &buf.addr;
820 socklen_t len = (socklen_t)sizeof buf;
821
822 GetOpenFile(sock, fptr);
823 sock2 = rsock_s_accept_nonblock(rb_cSocket, ex, fptr, addr, &len);
824
825 if (SYMBOL_P(sock2)) /* :wait_readable */
826 return sock2;
827 return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, &buf.addr, len));
828}
829
830/*
831 * call-seq:
832 * socket.sysaccept => [client_socket_fd, client_addrinfo]
833 *
834 * Accepts an incoming connection returning an array containing the (integer)
835 * file descriptor for the incoming connection, _client_socket_fd_,
836 * and an Addrinfo, _client_addrinfo_.
837 *
838 * === Example
839 * # In one script, start this first
840 * require 'socket'
841 * include Socket::Constants
842 * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
843 * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
844 * socket.bind( sockaddr )
845 * socket.listen( 5 )
846 * client_fd, client_addrinfo = socket.sysaccept
847 * client_socket = Socket.for_fd( client_fd )
848 * puts "The client said, '#{client_socket.readline.chomp}'"
849 * client_socket.puts "Hello from script one!"
850 * socket.close
851 *
852 * # In another script, start this second
853 * require 'socket'
854 * include Socket::Constants
855 * socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
856 * sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' )
857 * socket.connect( sockaddr )
858 * socket.puts "Hello from script 2."
859 * puts "The server said, '#{socket.readline.chomp}'"
860 * socket.close
861 *
862 * Refer to Socket#accept for the exceptions that may be thrown if the call
863 * to _sysaccept_ fails.
864 *
865 * === See
866 * * Socket#accept
867 */
868static VALUE
869sock_sysaccept(VALUE sock)
870{
871 rb_io_t *fptr;
872 VALUE sock2;
874 socklen_t len = (socklen_t)sizeof buf;
875
876 GetOpenFile(sock, fptr);
877 sock2 = rsock_s_accept(0,fptr->fd,&buf.addr,&len);
878
879 return rb_assoc_new(sock2, rsock_io_socket_addrinfo(sock2, &buf.addr, len));
880}
881
882#ifdef HAVE_GETHOSTNAME
883/*
884 * call-seq:
885 * Socket.gethostname => hostname
886 *
887 * Returns the hostname.
888 *
889 * p Socket.gethostname #=> "hal"
890 *
891 * Note that it is not guaranteed to be able to convert to IP address using gethostbyname, getaddrinfo, etc.
892 * If you need local IP address, use Socket.ip_address_list.
893 */
894static VALUE
896{
897#if defined(NI_MAXHOST)
898# define RUBY_MAX_HOST_NAME_LEN NI_MAXHOST
899#elif defined(HOST_NAME_MAX)
900# define RUBY_MAX_HOST_NAME_LEN HOST_NAME_MAX
901#else
902# define RUBY_MAX_HOST_NAME_LEN 1024
903#endif
904
905 long len = RUBY_MAX_HOST_NAME_LEN;
906 VALUE name;
907
908 name = rb_str_new(0, len);
909 while (gethostname(RSTRING_PTR(name), len) < 0) {
910 int e = errno;
911 switch (e) {
912 case ENAMETOOLONG:
913#ifdef __linux__
914 case EINVAL:
915 /* glibc before version 2.1 uses EINVAL instead of ENAMETOOLONG */
916#endif
917 break;
918 default:
919 rb_syserr_fail(e, "gethostname(3)");
920 }
922 len += len;
923 }
925 return name;
926}
927#else
928#ifdef HAVE_UNAME
929
930#include <sys/utsname.h>
931
932static VALUE
934{
935 struct utsname un;
936
937 uname(&un);
938 return rb_str_new2(un.nodename);
939}
940#else
941#define sock_gethostname rb_f_notimplement
942#endif
943#endif
944
945static VALUE
946make_addrinfo(struct rb_addrinfo *res0, int norevlookup)
947{
948 VALUE base, ary;
949 struct addrinfo *res;
950
951 if (res0 == NULL) {
952 rb_raise(rb_eSocket, "host not found");
953 }
954 base = rb_ary_new();
955 for (res = res0->ai; res; res = res->ai_next) {
956 ary = rsock_ipaddr(res->ai_addr, res->ai_addrlen, norevlookup);
957 if (res->ai_canonname) {
958 RARRAY_ASET(ary, 2, rb_str_new2(res->ai_canonname));
959 }
960 rb_ary_push(ary, INT2FIX(res->ai_family));
961 rb_ary_push(ary, INT2FIX(res->ai_socktype));
962 rb_ary_push(ary, INT2FIX(res->ai_protocol));
963 rb_ary_push(base, ary);
964 }
965 return base;
966}
967
968static VALUE
969sock_sockaddr(struct sockaddr *addr, socklen_t len)
970{
971 char *ptr;
972
973 switch (addr->sa_family) {
974 case AF_INET:
975 ptr = (char*)&((struct sockaddr_in*)addr)->sin_addr.s_addr;
976 len = (socklen_t)sizeof(((struct sockaddr_in*)addr)->sin_addr.s_addr);
977 break;
978#ifdef AF_INET6
979 case AF_INET6:
980 ptr = (char*)&((struct sockaddr_in6*)addr)->sin6_addr.s6_addr;
981 len = (socklen_t)sizeof(((struct sockaddr_in6*)addr)->sin6_addr.s6_addr);
982 break;
983#endif
984 default:
985 rb_raise(rb_eSocket, "unknown socket family:%d", addr->sa_family);
986 break;
987 }
988 return rb_str_new(ptr, len);
989}
990
991/*
992 * call-seq:
993 * Socket.gethostbyname(hostname) => [official_hostname, alias_hostnames, address_family, *address_list]
994 *
995 * Use Addrinfo.getaddrinfo instead.
996 * This method is deprecated for the following reasons:
997 *
998 * - The 3rd element of the result is the address family of the first address.
999 * The address families of the rest of the addresses are not returned.
1000 * - Uncommon address representation:
1001 * 4/16-bytes binary string to represent IPv4/IPv6 address.
1002 * - gethostbyname() may take a long time and it may block other threads.
1003 * (GVL cannot be released since gethostbyname() is not thread safe.)
1004 * - This method uses gethostbyname() function already removed from POSIX.
1005 *
1006 * This method obtains the host information for _hostname_.
1007 *
1008 * p Socket.gethostbyname("hal") #=> ["localhost", ["hal"], 2, "\x7F\x00\x00\x01"]
1009 *
1010 */
1011static VALUE
1012sock_s_gethostbyname(VALUE obj, VALUE host)
1013{
1014 struct rb_addrinfo *res =
1015 rsock_addrinfo(host, Qnil, AF_UNSPEC, SOCK_STREAM, AI_CANONNAME);
1016 return rsock_make_hostent(host, res, sock_sockaddr);
1017}
1018
1019/*
1020 * call-seq:
1021 * Socket.gethostbyaddr(address_string [, address_family]) => hostent
1022 *
1023 * Use Addrinfo#getnameinfo instead.
1024 * This method is deprecated for the following reasons:
1025 *
1026 * - Uncommon address representation:
1027 * 4/16-bytes binary string to represent IPv4/IPv6 address.
1028 * - gethostbyaddr() may take a long time and it may block other threads.
1029 * (GVL cannot be released since gethostbyname() is not thread safe.)
1030 * - This method uses gethostbyname() function already removed from POSIX.
1031 *
1032 * This method obtains the host information for _address_.
1033 *
1034 * p Socket.gethostbyaddr([221,186,184,68].pack("CCCC"))
1035 * #=> ["carbon.ruby-lang.org", [], 2, "\xDD\xBA\xB8D"]
1036 *
1037 * p Socket.gethostbyaddr([127,0,0,1].pack("CCCC"))
1038 * ["localhost", [], 2, "\x7F\x00\x00\x01"]
1039 * p Socket.gethostbyaddr(([0]*15+[1]).pack("C"*16))
1040 * #=> ["localhost", ["ip6-localhost", "ip6-loopback"], 10,
1041 * "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"]
1042 *
1043 */
1044static VALUE
1045sock_s_gethostbyaddr(int argc, VALUE *argv, VALUE _)
1046{
1047 VALUE addr, family;
1048 struct hostent *h;
1049 char **pch;
1050 VALUE ary, names;
1051 int t = AF_INET;
1052
1053 rb_scan_args(argc, argv, "11", &addr, &family);
1054 StringValue(addr);
1055 if (!NIL_P(family)) {
1056 t = rsock_family_arg(family);
1057 }
1058#ifdef AF_INET6
1059 else if (RSTRING_LEN(addr) == 16) {
1060 t = AF_INET6;
1061 }
1062#endif
1063 h = gethostbyaddr(RSTRING_PTR(addr), RSTRING_SOCKLEN(addr), t);
1064 if (h == NULL) {
1065#ifdef HAVE_HSTRERROR
1066 extern int h_errno;
1067 rb_raise(rb_eSocket, "%s", (char*)hstrerror(h_errno));
1068#else
1069 rb_raise(rb_eSocket, "host not found");
1070#endif
1071 }
1072 ary = rb_ary_new();
1073 rb_ary_push(ary, rb_str_new2(h->h_name));
1074 names = rb_ary_new();
1075 rb_ary_push(ary, names);
1076 if (h->h_aliases != NULL) {
1077 for (pch = h->h_aliases; *pch; pch++) {
1079 }
1080 }
1081 rb_ary_push(ary, INT2NUM(h->h_addrtype));
1082#ifdef h_addr
1083 for (pch = h->h_addr_list; *pch; pch++) {
1084 rb_ary_push(ary, rb_str_new(*pch, h->h_length));
1085 }
1086#else
1087 rb_ary_push(ary, rb_str_new(h->h_addr, h->h_length));
1088#endif
1089
1090 return ary;
1091}
1092
1093/*
1094 * call-seq:
1095 * Socket.getservbyname(service_name) => port_number
1096 * Socket.getservbyname(service_name, protocol_name) => port_number
1097 *
1098 * Obtains the port number for _service_name_.
1099 *
1100 * If _protocol_name_ is not given, "tcp" is assumed.
1101 *
1102 * Socket.getservbyname("smtp") #=> 25
1103 * Socket.getservbyname("shell") #=> 514
1104 * Socket.getservbyname("syslog", "udp") #=> 514
1105 */
1106static VALUE
1107sock_s_getservbyname(int argc, VALUE *argv, VALUE _)
1108{
1109 VALUE service, proto;
1110 struct servent *sp;
1111 long port;
1112 const char *servicename, *protoname = "tcp";
1113
1114 rb_scan_args(argc, argv, "11", &service, &proto);
1115 StringValue(service);
1116 if (!NIL_P(proto)) StringValue(proto);
1117 servicename = StringValueCStr(service);
1118 if (!NIL_P(proto)) protoname = StringValueCStr(proto);
1119 sp = getservbyname(servicename, protoname);
1120 if (sp) {
1121 port = ntohs(sp->s_port);
1122 }
1123 else {
1124 char *end;
1125
1126 port = STRTOUL(servicename, &end, 0);
1127 if (*end != '\0') {
1128 rb_raise(rb_eSocket, "no such service %s/%s", servicename, protoname);
1129 }
1130 }
1131 return INT2FIX(port);
1132}
1133
1134/*
1135 * call-seq:
1136 * Socket.getservbyport(port [, protocol_name]) => service
1137 *
1138 * Obtains the port number for _port_.
1139 *
1140 * If _protocol_name_ is not given, "tcp" is assumed.
1141 *
1142 * Socket.getservbyport(80) #=> "www"
1143 * Socket.getservbyport(514, "tcp") #=> "shell"
1144 * Socket.getservbyport(514, "udp") #=> "syslog"
1145 *
1146 */
1147static VALUE
1148sock_s_getservbyport(int argc, VALUE *argv, VALUE _)
1149{
1150 VALUE port, proto;
1151 struct servent *sp;
1152 long portnum;
1153 const char *protoname = "tcp";
1154
1155 rb_scan_args(argc, argv, "11", &port, &proto);
1156 portnum = NUM2LONG(port);
1157 if (portnum != (uint16_t)portnum) {
1158 const char *s = portnum > 0 ? "big" : "small";
1159 rb_raise(rb_eRangeError, "integer %ld too %s to convert into `int16_t'", portnum, s);
1160 }
1161 if (!NIL_P(proto)) protoname = StringValueCStr(proto);
1162
1163 sp = getservbyport((int)htons((uint16_t)portnum), protoname);
1164 if (!sp) {
1165 rb_raise(rb_eSocket, "no such service for port %d/%s", (int)portnum, protoname);
1166 }
1167 return rb_str_new2(sp->s_name);
1168}
1169
1170/*
1171 * call-seq:
1172 * Socket.getaddrinfo(nodename, servname[, family[, socktype[, protocol[, flags[, reverse_lookup]]]]]) => array
1173 *
1174 * Obtains address information for _nodename_:_servname_.
1175 *
1176 * Note that Addrinfo.getaddrinfo provides the same functionality in
1177 * an object oriented style.
1178 *
1179 * _family_ should be an address family such as: :INET, :INET6, etc.
1180 *
1181 * _socktype_ should be a socket type such as: :STREAM, :DGRAM, :RAW, etc.
1182 *
1183 * _protocol_ should be a protocol defined in the family,
1184 * and defaults to 0 for the family.
1185 *
1186 * _flags_ should be bitwise OR of Socket::AI_* constants.
1187 *
1188 * Socket.getaddrinfo("www.ruby-lang.org", "http", nil, :STREAM)
1189 * #=> [["AF_INET", 80, "carbon.ruby-lang.org", "221.186.184.68", 2, 1, 6]] # PF_INET/SOCK_STREAM/IPPROTO_TCP
1190 *
1191 * Socket.getaddrinfo("localhost", nil)
1192 * #=> [["AF_INET", 0, "localhost", "127.0.0.1", 2, 1, 6], # PF_INET/SOCK_STREAM/IPPROTO_TCP
1193 * # ["AF_INET", 0, "localhost", "127.0.0.1", 2, 2, 17], # PF_INET/SOCK_DGRAM/IPPROTO_UDP
1194 * # ["AF_INET", 0, "localhost", "127.0.0.1", 2, 3, 0]] # PF_INET/SOCK_RAW/IPPROTO_IP
1195 *
1196 * _reverse_lookup_ directs the form of the third element, and has to
1197 * be one of below. If _reverse_lookup_ is omitted, the default value is +nil+.
1198 *
1199 * +true+, +:hostname+: hostname is obtained from numeric address using reverse lookup, which may take a time.
1200 * +false+, +:numeric+: hostname is same as numeric address.
1201 * +nil+: obey to the current +do_not_reverse_lookup+ flag.
1202 *
1203 * If Addrinfo object is preferred, use Addrinfo.getaddrinfo.
1204 */
1205static VALUE
1206sock_s_getaddrinfo(int argc, VALUE *argv, VALUE _)
1207{
1208 VALUE host, port, family, socktype, protocol, flags, ret, revlookup;
1209 struct addrinfo hints;
1210 struct rb_addrinfo *res;
1211 int norevlookup;
1212
1213 rb_scan_args(argc, argv, "25", &host, &port, &family, &socktype, &protocol, &flags, &revlookup);
1214
1215 MEMZERO(&hints, struct addrinfo, 1);
1216 hints.ai_family = NIL_P(family) ? PF_UNSPEC : rsock_family_arg(family);
1217
1218 if (!NIL_P(socktype)) {
1219 hints.ai_socktype = rsock_socktype_arg(socktype);
1220 }
1221 if (!NIL_P(protocol)) {
1222 hints.ai_protocol = NUM2INT(protocol);
1223 }
1224 if (!NIL_P(flags)) {
1225 hints.ai_flags = NUM2INT(flags);
1226 }
1227 if (NIL_P(revlookup) || !rsock_revlookup_flag(revlookup, &norevlookup)) {
1228 norevlookup = rsock_do_not_reverse_lookup;
1229 }
1230 res = rsock_getaddrinfo(host, port, &hints, 0);
1231
1232 ret = make_addrinfo(res, norevlookup);
1233 rb_freeaddrinfo(res);
1234 return ret;
1235}
1236
1237/*
1238 * call-seq:
1239 * Socket.getnameinfo(sockaddr [, flags]) => [hostname, servicename]
1240 *
1241 * Obtains name information for _sockaddr_.
1242 *
1243 * _sockaddr_ should be one of follows.
1244 * - packed sockaddr string such as Socket.sockaddr_in(80, "127.0.0.1")
1245 * - 3-elements array such as ["AF_INET", 80, "127.0.0.1"]
1246 * - 4-elements array such as ["AF_INET", 80, ignored, "127.0.0.1"]
1247 *
1248 * _flags_ should be bitwise OR of Socket::NI_* constants.
1249 *
1250 * Note:
1251 * The last form is compatible with IPSocket#addr and IPSocket#peeraddr.
1252 *
1253 * Socket.getnameinfo(Socket.sockaddr_in(80, "127.0.0.1")) #=> ["localhost", "www"]
1254 * Socket.getnameinfo(["AF_INET", 80, "127.0.0.1"]) #=> ["localhost", "www"]
1255 * Socket.getnameinfo(["AF_INET", 80, "localhost", "127.0.0.1"]) #=> ["localhost", "www"]
1256 *
1257 * If Addrinfo object is preferred, use Addrinfo#getnameinfo.
1258 */
1259static VALUE
1260sock_s_getnameinfo(int argc, VALUE *argv, VALUE _)
1261{
1262 VALUE sa, af = Qnil, host = Qnil, port = Qnil, flags, tmp;
1263 char *hptr, *pptr;
1264 char hbuf[1024], pbuf[1024];
1265 int fl;
1266 struct rb_addrinfo *res = NULL;
1267 struct addrinfo hints, *r;
1268 int error, saved_errno;
1269 union_sockaddr ss;
1270 struct sockaddr *sap;
1271 socklen_t salen;
1272
1273 sa = flags = Qnil;
1274 rb_scan_args(argc, argv, "11", &sa, &flags);
1275
1276 fl = 0;
1277 if (!NIL_P(flags)) {
1278 fl = NUM2INT(flags);
1279 }
1281 if (!NIL_P(tmp)) {
1282 sa = tmp;
1283 if (sizeof(ss) < (size_t)RSTRING_LEN(sa)) {
1284 rb_raise(rb_eTypeError, "sockaddr length too big");
1285 }
1286 memcpy(&ss, RSTRING_PTR(sa), RSTRING_LEN(sa));
1287 if (!VALIDATE_SOCKLEN(&ss.addr, RSTRING_LEN(sa))) {
1288 rb_raise(rb_eTypeError, "sockaddr size differs - should not happen");
1289 }
1290 sap = &ss.addr;
1291 salen = RSTRING_SOCKLEN(sa);
1292 goto call_nameinfo;
1293 }
1294 tmp = rb_check_array_type(sa);
1295 if (!NIL_P(tmp)) {
1296 sa = tmp;
1297 MEMZERO(&hints, struct addrinfo, 1);
1298 if (RARRAY_LEN(sa) == 3) {
1299 af = RARRAY_AREF(sa, 0);
1300 port = RARRAY_AREF(sa, 1);
1301 host = RARRAY_AREF(sa, 2);
1302 }
1303 else if (RARRAY_LEN(sa) >= 4) {
1304 af = RARRAY_AREF(sa, 0);
1305 port = RARRAY_AREF(sa, 1);
1306 host = RARRAY_AREF(sa, 3);
1307 if (NIL_P(host)) {
1308 host = RARRAY_AREF(sa, 2);
1309 }
1310 else {
1311 /*
1312 * 4th element holds numeric form, don't resolve.
1313 * see rsock_ipaddr().
1314 */
1315#ifdef AI_NUMERICHOST /* AIX 4.3.3 doesn't have AI_NUMERICHOST. */
1316 hints.ai_flags |= AI_NUMERICHOST;
1317#endif
1318 }
1319 }
1320 else {
1321 rb_raise(rb_eArgError, "array size should be 3 or 4, %ld given",
1322 RARRAY_LEN(sa));
1323 }
1324 /* host */
1325 if (NIL_P(host)) {
1326 hptr = NULL;
1327 }
1328 else {
1329 strncpy(hbuf, StringValueCStr(host), sizeof(hbuf));
1330 hbuf[sizeof(hbuf) - 1] = '\0';
1331 hptr = hbuf;
1332 }
1333 /* port */
1334 if (NIL_P(port)) {
1335 strcpy(pbuf, "0");
1336 pptr = NULL;
1337 }
1338 else if (FIXNUM_P(port)) {
1339 snprintf(pbuf, sizeof(pbuf), "%ld", NUM2LONG(port));
1340 pptr = pbuf;
1341 }
1342 else {
1343 strncpy(pbuf, StringValueCStr(port), sizeof(pbuf));
1344 pbuf[sizeof(pbuf) - 1] = '\0';
1345 pptr = pbuf;
1346 }
1347 hints.ai_socktype = (fl & NI_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
1348 /* af */
1349 hints.ai_family = NIL_P(af) ? PF_UNSPEC : rsock_family_arg(af);
1350 error = rb_getaddrinfo(hptr, pptr, &hints, &res);
1351 if (error) goto error_exit_addr;
1352 sap = res->ai->ai_addr;
1353 salen = res->ai->ai_addrlen;
1354 }
1355 else {
1356 rb_raise(rb_eTypeError, "expecting String or Array");
1357 }
1358
1359 call_nameinfo:
1360 error = rb_getnameinfo(sap, salen, hbuf, sizeof(hbuf),
1361 pbuf, sizeof(pbuf), fl);
1362 if (error) goto error_exit_name;
1363 if (res) {
1364 for (r = res->ai->ai_next; r; r = r->ai_next) {
1365 char hbuf2[1024], pbuf2[1024];
1366
1367 sap = r->ai_addr;
1368 salen = r->ai_addrlen;
1369 error = rb_getnameinfo(sap, salen, hbuf2, sizeof(hbuf2),
1370 pbuf2, sizeof(pbuf2), fl);
1371 if (error) goto error_exit_name;
1372 if (strcmp(hbuf, hbuf2) != 0|| strcmp(pbuf, pbuf2) != 0) {
1373 rb_freeaddrinfo(res);
1374 rb_raise(rb_eSocket, "sockaddr resolved to multiple nodename");
1375 }
1376 }
1377 rb_freeaddrinfo(res);
1378 }
1379 return rb_assoc_new(rb_str_new2(hbuf), rb_str_new2(pbuf));
1380
1381 error_exit_addr:
1382 saved_errno = errno;
1383 if (res) rb_freeaddrinfo(res);
1384 errno = saved_errno;
1385 rsock_raise_socket_error("getaddrinfo", error);
1386
1387 error_exit_name:
1388 saved_errno = errno;
1389 if (res) rb_freeaddrinfo(res);
1390 errno = saved_errno;
1391 rsock_raise_socket_error("getnameinfo", error);
1392
1394}
1395
1396/*
1397 * call-seq:
1398 * Socket.sockaddr_in(port, host) => sockaddr
1399 * Socket.pack_sockaddr_in(port, host) => sockaddr
1400 *
1401 * Packs _port_ and _host_ as an AF_INET/AF_INET6 sockaddr string.
1402 *
1403 * Socket.sockaddr_in(80, "127.0.0.1")
1404 * #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
1405 *
1406 * Socket.sockaddr_in(80, "::1")
1407 * #=> "\n\x00\x00P\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00"
1408 *
1409 */
1410static VALUE
1411sock_s_pack_sockaddr_in(VALUE self, VALUE port, VALUE host)
1412{
1413 struct rb_addrinfo *res = rsock_addrinfo(host, port, AF_UNSPEC, 0, 0);
1414 VALUE addr = rb_str_new((char*)res->ai->ai_addr, res->ai->ai_addrlen);
1415
1416 rb_freeaddrinfo(res);
1417
1418 return addr;
1419}
1420
1421/*
1422 * call-seq:
1423 * Socket.unpack_sockaddr_in(sockaddr) => [port, ip_address]
1424 *
1425 * Unpacks _sockaddr_ into port and ip_address.
1426 *
1427 * _sockaddr_ should be a string or an addrinfo for AF_INET/AF_INET6.
1428 *
1429 * sockaddr = Socket.sockaddr_in(80, "127.0.0.1")
1430 * p sockaddr #=> "\x02\x00\x00P\x7F\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
1431 * p Socket.unpack_sockaddr_in(sockaddr) #=> [80, "127.0.0.1"]
1432 *
1433 */
1434static VALUE
1435sock_s_unpack_sockaddr_in(VALUE self, VALUE addr)
1436{
1437 struct sockaddr_in * sockaddr;
1438 VALUE host;
1439
1440 sockaddr = (struct sockaddr_in*)SockAddrStringValuePtr(addr);
1441 if (RSTRING_LEN(addr) <
1442 (char*)&((struct sockaddr *)sockaddr)->sa_family +
1443 sizeof(((struct sockaddr *)sockaddr)->sa_family) -
1444 (char*)sockaddr)
1445 rb_raise(rb_eArgError, "too short sockaddr");
1446 if (((struct sockaddr *)sockaddr)->sa_family != AF_INET
1447#ifdef INET6
1448 && ((struct sockaddr *)sockaddr)->sa_family != AF_INET6
1449#endif
1450 ) {
1451#ifdef INET6
1452 rb_raise(rb_eArgError, "not an AF_INET/AF_INET6 sockaddr");
1453#else
1454 rb_raise(rb_eArgError, "not an AF_INET sockaddr");
1455#endif
1456 }
1457 host = rsock_make_ipaddr((struct sockaddr*)sockaddr, RSTRING_SOCKLEN(addr));
1458 return rb_assoc_new(INT2NUM(ntohs(sockaddr->sin_port)), host);
1459}
1460
1461#ifdef HAVE_SYS_UN_H
1462
1463/*
1464 * call-seq:
1465 * Socket.sockaddr_un(path) => sockaddr
1466 * Socket.pack_sockaddr_un(path) => sockaddr
1467 *
1468 * Packs _path_ as an AF_UNIX sockaddr string.
1469 *
1470 * Socket.sockaddr_un("/tmp/sock") #=> "\x01\x00/tmp/sock\x00\x00..."
1471 *
1472 */
1473static VALUE
1474sock_s_pack_sockaddr_un(VALUE self, VALUE path)
1475{
1476 struct sockaddr_un sockaddr;
1477 VALUE addr;
1478
1480 INIT_SOCKADDR_UN(&sockaddr, sizeof(struct sockaddr_un));
1481 if (sizeof(sockaddr.sun_path) < (size_t)RSTRING_LEN(path)) {
1482 rb_raise(rb_eArgError, "too long unix socket path (%"PRIuSIZE" bytes given but %"PRIuSIZE" bytes max)",
1483 (size_t)RSTRING_LEN(path), sizeof(sockaddr.sun_path));
1484 }
1485 memcpy(sockaddr.sun_path, RSTRING_PTR(path), RSTRING_LEN(path));
1486 addr = rb_str_new((char*)&sockaddr, rsock_unix_sockaddr_len(path));
1487
1488 return addr;
1489}
1490
1491/*
1492 * call-seq:
1493 * Socket.unpack_sockaddr_un(sockaddr) => path
1494 *
1495 * Unpacks _sockaddr_ into path.
1496 *
1497 * _sockaddr_ should be a string or an addrinfo for AF_UNIX.
1498 *
1499 * sockaddr = Socket.sockaddr_un("/tmp/sock")
1500 * p Socket.unpack_sockaddr_un(sockaddr) #=> "/tmp/sock"
1501 *
1502 */
1503static VALUE
1504sock_s_unpack_sockaddr_un(VALUE self, VALUE addr)
1505{
1506 struct sockaddr_un * sockaddr;
1507 VALUE path;
1508
1509 sockaddr = (struct sockaddr_un*)SockAddrStringValuePtr(addr);
1510 if (RSTRING_LEN(addr) <
1511 (char*)&((struct sockaddr *)sockaddr)->sa_family +
1512 sizeof(((struct sockaddr *)sockaddr)->sa_family) -
1513 (char*)sockaddr)
1514 rb_raise(rb_eArgError, "too short sockaddr");
1515 if (((struct sockaddr *)sockaddr)->sa_family != AF_UNIX) {
1516 rb_raise(rb_eArgError, "not an AF_UNIX sockaddr");
1517 }
1518 if (sizeof(struct sockaddr_un) < (size_t)RSTRING_LEN(addr)) {
1519 rb_raise(rb_eTypeError, "too long sockaddr_un - %ld longer than %d",
1520 RSTRING_LEN(addr), (int)sizeof(struct sockaddr_un));
1521 }
1522 path = rsock_unixpath_str(sockaddr, RSTRING_SOCKLEN(addr));
1523 return path;
1524}
1525#endif
1526
1527#if defined(HAVE_GETIFADDRS) || defined(SIOCGLIFCONF) || defined(SIOCGIFCONF) || defined(_WIN32)
1528
1529static socklen_t
1530sockaddr_len(struct sockaddr *addr)
1531{
1532 if (addr == NULL)
1533 return 0;
1534
1535#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
1536 if (addr->sa_len != 0)
1537 return addr->sa_len;
1538#endif
1539
1540 switch (addr->sa_family) {
1541 case AF_INET:
1542 return (socklen_t)sizeof(struct sockaddr_in);
1543
1544#ifdef AF_INET6
1545 case AF_INET6:
1546 return (socklen_t)sizeof(struct sockaddr_in6);
1547#endif
1548
1549#ifdef HAVE_SYS_UN_H
1550 case AF_UNIX:
1551 return (socklen_t)sizeof(struct sockaddr_un);
1552#endif
1553
1554#ifdef AF_PACKET
1555 case AF_PACKET:
1556 return (socklen_t)(offsetof(struct sockaddr_ll, sll_addr) + ((struct sockaddr_ll *)addr)->sll_halen);
1557#endif
1558
1559 default:
1560 return (socklen_t)(offsetof(struct sockaddr, sa_family) + sizeof(addr->sa_family));
1561 }
1562}
1563
1565rsock_sockaddr_len(struct sockaddr *addr)
1566{
1567 return sockaddr_len(addr);
1568}
1569
1570static VALUE
1571sockaddr_obj(struct sockaddr *addr, socklen_t len)
1572{
1573#if defined(AF_INET6) && defined(__KAME__)
1574 struct sockaddr_in6 addr6;
1575#endif
1576
1577 if (addr == NULL)
1578 return Qnil;
1579
1580 len = sockaddr_len(addr);
1581
1582#if defined(__KAME__) && defined(AF_INET6)
1583 if (addr->sa_family == AF_INET6) {
1584 /* KAME uses the 2nd 16bit word of link local IPv6 address as interface index internally */
1585 /* http://orange.kame.net/dev/cvsweb.cgi/kame/IMPLEMENTATION */
1586 /* convert fe80:1::1 to fe80::1%1 */
1587 len = (socklen_t)sizeof(struct sockaddr_in6);
1588 memcpy(&addr6, addr, len);
1589 addr = (struct sockaddr *)&addr6;
1590 if (IN6_IS_ADDR_LINKLOCAL(&addr6.sin6_addr) &&
1591 addr6.sin6_scope_id == 0 &&
1592 (addr6.sin6_addr.s6_addr[2] || addr6.sin6_addr.s6_addr[3])) {
1593 addr6.sin6_scope_id = (addr6.sin6_addr.s6_addr[2] << 8) | addr6.sin6_addr.s6_addr[3];
1594 addr6.sin6_addr.s6_addr[2] = 0;
1595 addr6.sin6_addr.s6_addr[3] = 0;
1596 }
1597 }
1598#endif
1599
1600 return rsock_addrinfo_new(addr, len, addr->sa_family, 0, 0, Qnil, Qnil);
1601}
1602
1603VALUE
1604rsock_sockaddr_obj(struct sockaddr *addr, socklen_t len)
1605{
1606 return sockaddr_obj(addr, len);
1607}
1608
1609#endif
1610
1611#if defined(HAVE_GETIFADDRS) || (defined(SIOCGLIFCONF) && defined(SIOCGLIFNUM) && !defined(__hpux)) || defined(SIOCGIFCONF) || defined(_WIN32)
1612/*
1613 * call-seq:
1614 * Socket.ip_address_list => array
1615 *
1616 * Returns local IP addresses as an array.
1617 *
1618 * The array contains Addrinfo objects.
1619 *
1620 * pp Socket.ip_address_list
1621 * #=> [#<Addrinfo: 127.0.0.1>,
1622 * #<Addrinfo: 192.168.0.128>,
1623 * #<Addrinfo: ::1>,
1624 * ...]
1625 *
1626 */
1627static VALUE
1629{
1630#if defined(HAVE_GETIFADDRS)
1631 struct ifaddrs *ifp = NULL;
1632 struct ifaddrs *p;
1633 int ret;
1634 VALUE list;
1635
1636 ret = getifaddrs(&ifp);
1637 if (ret == -1) {
1638 rb_sys_fail("getifaddrs");
1639 }
1640
1641 list = rb_ary_new();
1642 for (p = ifp; p; p = p->ifa_next) {
1643 if (p->ifa_addr != NULL && IS_IP_FAMILY(p->ifa_addr->sa_family)) {
1644 struct sockaddr *addr = p->ifa_addr;
1645#if defined(AF_INET6) && defined(__sun)
1646 /*
1647 * OpenIndiana SunOS 5.11 getifaddrs() returns IPv6 link local
1648 * address with sin6_scope_id == 0.
1649 * So fill it from the interface name (ifa_name).
1650 */
1651 struct sockaddr_in6 addr6;
1652 if (addr->sa_family == AF_INET6) {
1653 socklen_t len = (socklen_t)sizeof(struct sockaddr_in6);
1654 memcpy(&addr6, addr, len);
1655 addr = (struct sockaddr *)&addr6;
1656 if (IN6_IS_ADDR_LINKLOCAL(&addr6.sin6_addr) &&
1657 addr6.sin6_scope_id == 0) {
1658 unsigned int ifindex = if_nametoindex(p->ifa_name);
1659 if (ifindex != 0) {
1660 addr6.sin6_scope_id = ifindex;
1661 }
1662 }
1663 }
1664#endif
1665 rb_ary_push(list, sockaddr_obj(addr, sockaddr_len(addr)));
1666 }
1667 }
1668
1669 freeifaddrs(ifp);
1670
1671 return list;
1672#elif defined(SIOCGLIFCONF) && defined(SIOCGLIFNUM) && !defined(__hpux)
1673 /* Solaris if_tcp(7P) */
1674 /* HP-UX has SIOCGLIFCONF too. But it uses different struct */
1675 int fd = -1;
1676 int ret;
1677 struct lifnum ln;
1678 struct lifconf lc;
1679 const char *reason = NULL;
1680 int save_errno;
1681 int i;
1682 VALUE list = Qnil;
1683
1684 lc.lifc_buf = NULL;
1685
1686 fd = socket(AF_INET, SOCK_DGRAM, 0);
1687 if (fd == -1)
1688 rb_sys_fail("socket(2)");
1689
1690 memset(&ln, 0, sizeof(ln));
1691 ln.lifn_family = AF_UNSPEC;
1692
1693 ret = ioctl(fd, SIOCGLIFNUM, &ln);
1694 if (ret == -1) {
1695 reason = "SIOCGLIFNUM";
1696 goto finish;
1697 }
1698
1699 memset(&lc, 0, sizeof(lc));
1700 lc.lifc_family = AF_UNSPEC;
1701 lc.lifc_flags = 0;
1702 lc.lifc_len = sizeof(struct lifreq) * ln.lifn_count;
1703 lc.lifc_req = xmalloc(lc.lifc_len);
1704
1705 ret = ioctl(fd, SIOCGLIFCONF, &lc);
1706 if (ret == -1) {
1707 reason = "SIOCGLIFCONF";
1708 goto finish;
1709 }
1710
1711 list = rb_ary_new();
1712 for (i = 0; i < ln.lifn_count; i++) {
1713 struct lifreq *req = &lc.lifc_req[i];
1714 if (IS_IP_FAMILY(req->lifr_addr.ss_family)) {
1715 if (req->lifr_addr.ss_family == AF_INET6 &&
1716 IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_addr) &&
1717 ((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_scope_id == 0) {
1718 struct lifreq req2;
1719 memcpy(req2.lifr_name, req->lifr_name, LIFNAMSIZ);
1720 ret = ioctl(fd, SIOCGLIFINDEX, &req2);
1721 if (ret == -1) {
1722 reason = "SIOCGLIFINDEX";
1723 goto finish;
1724 }
1725 ((struct sockaddr_in6 *)(&req->lifr_addr))->sin6_scope_id = req2.lifr_index;
1726 }
1727 rb_ary_push(list, sockaddr_obj((struct sockaddr *)&req->lifr_addr, req->lifr_addrlen));
1728 }
1729 }
1730
1731 finish:
1732 save_errno = errno;
1733 if (lc.lifc_buf != NULL)
1734 xfree(lc.lifc_req);
1735 if (fd != -1)
1736 close(fd);
1737 errno = save_errno;
1738
1739 if (reason)
1740 rb_syserr_fail(save_errno, reason);
1741 return list;
1742
1743#elif defined(SIOCGIFCONF)
1744 int fd = -1;
1745 int ret;
1746#define EXTRA_SPACE ((int)(sizeof(struct ifconf) + sizeof(union_sockaddr)))
1747 char initbuf[4096+EXTRA_SPACE];
1748 char *buf = initbuf;
1749 int bufsize;
1750 struct ifconf conf;
1751 struct ifreq *req;
1752 VALUE list = Qnil;
1753 const char *reason = NULL;
1754 int save_errno;
1755
1756 fd = socket(AF_INET, SOCK_DGRAM, 0);
1757 if (fd == -1)
1758 rb_sys_fail("socket(2)");
1759
1760 bufsize = sizeof(initbuf);
1761 buf = initbuf;
1762
1763 retry:
1764 conf.ifc_len = bufsize;
1765 conf.ifc_req = (struct ifreq *)buf;
1766
1767 /* fprintf(stderr, "bufsize: %d\n", bufsize); */
1768
1769 ret = ioctl(fd, SIOCGIFCONF, &conf);
1770 if (ret == -1) {
1771 reason = "SIOCGIFCONF";
1772 goto finish;
1773 }
1774
1775 /* fprintf(stderr, "conf.ifc_len: %d\n", conf.ifc_len); */
1776
1777 if (bufsize - EXTRA_SPACE < conf.ifc_len) {
1778 if (bufsize < conf.ifc_len) {
1779 /* NetBSD returns required size for all interfaces. */
1780 bufsize = conf.ifc_len + EXTRA_SPACE;
1781 }
1782 else {
1783 bufsize = bufsize << 1;
1784 }
1785 if (buf == initbuf)
1786 buf = NULL;
1787 buf = xrealloc(buf, bufsize);
1788 goto retry;
1789 }
1790
1791 close(fd);
1792 fd = -1;
1793
1794 list = rb_ary_new();
1795 req = conf.ifc_req;
1796 while ((char*)req < (char*)conf.ifc_req + conf.ifc_len) {
1797 struct sockaddr *addr = &req->ifr_addr;
1798 if (IS_IP_FAMILY(addr->sa_family)) {
1799 rb_ary_push(list, sockaddr_obj(addr, sockaddr_len(addr)));
1800 }
1801#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
1802# ifndef _SIZEOF_ADDR_IFREQ
1803# define _SIZEOF_ADDR_IFREQ(r) \
1804 (sizeof(struct ifreq) + \
1805 (sizeof(struct sockaddr) < (r).ifr_addr.sa_len ? \
1806 (r).ifr_addr.sa_len - sizeof(struct sockaddr) : \
1807 0))
1808# endif
1809 req = (struct ifreq *)((char*)req + _SIZEOF_ADDR_IFREQ(*req));
1810#else
1811 req = (struct ifreq *)((char*)req + sizeof(struct ifreq));
1812#endif
1813 }
1814
1815 finish:
1816
1817 save_errno = errno;
1818 if (buf != initbuf)
1819 xfree(buf);
1820 if (fd != -1)
1821 close(fd);
1822 errno = save_errno;
1823
1824 if (reason)
1825 rb_syserr_fail(save_errno, reason);
1826 return list;
1827
1828#undef EXTRA_SPACE
1829#elif defined(_WIN32)
1830 typedef struct ip_adapter_unicast_address_st {
1831 unsigned LONG_LONG dummy0;
1832 struct ip_adapter_unicast_address_st *Next;
1833 struct {
1834 struct sockaddr *lpSockaddr;
1835 int iSockaddrLength;
1836 } Address;
1837 int dummy1;
1838 int dummy2;
1839 int dummy3;
1840 long dummy4;
1841 long dummy5;
1842 long dummy6;
1843 } ip_adapter_unicast_address_t;
1844 typedef struct ip_adapter_anycast_address_st {
1845 unsigned LONG_LONG dummy0;
1846 struct ip_adapter_anycast_address_st *Next;
1847 struct {
1848 struct sockaddr *lpSockaddr;
1849 int iSockaddrLength;
1850 } Address;
1851 } ip_adapter_anycast_address_t;
1852 typedef struct ip_adapter_addresses_st {
1853 unsigned LONG_LONG dummy0;
1854 struct ip_adapter_addresses_st *Next;
1855 void *dummy1;
1856 ip_adapter_unicast_address_t *FirstUnicastAddress;
1857 ip_adapter_anycast_address_t *FirstAnycastAddress;
1858 void *dummy2;
1859 void *dummy3;
1860 void *dummy4;
1861 void *dummy5;
1862 void *dummy6;
1863 BYTE dummy7[8];
1864 DWORD dummy8;
1865 DWORD dummy9;
1866 DWORD dummy10;
1867 DWORD IfType;
1868 int OperStatus;
1869 DWORD dummy12;
1870 DWORD dummy13[16];
1871 void *dummy14;
1872 } ip_adapter_addresses_t;
1873 typedef ULONG (WINAPI *GetAdaptersAddresses_t)(ULONG, ULONG, PVOID, ip_adapter_addresses_t *, PULONG);
1874 HMODULE h;
1875 GetAdaptersAddresses_t pGetAdaptersAddresses;
1876 ULONG len;
1877 DWORD ret;
1878 ip_adapter_addresses_t *adapters;
1879 VALUE list;
1880
1881 h = LoadLibrary("iphlpapi.dll");
1882 if (!h)
1884 pGetAdaptersAddresses = (GetAdaptersAddresses_t)GetProcAddress(h, "GetAdaptersAddresses");
1885 if (!pGetAdaptersAddresses) {
1886 FreeLibrary(h);
1888 }
1889
1890 ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &len);
1891 if (ret != ERROR_SUCCESS && ret != ERROR_BUFFER_OVERFLOW) {
1892 errno = rb_w32_map_errno(ret);
1893 FreeLibrary(h);
1894 rb_sys_fail("GetAdaptersAddresses");
1895 }
1896 adapters = (ip_adapter_addresses_t *)ALLOCA_N(BYTE, len);
1897 ret = pGetAdaptersAddresses(AF_UNSPEC, 0, NULL, adapters, &len);
1898 if (ret != ERROR_SUCCESS) {
1899 errno = rb_w32_map_errno(ret);
1900 FreeLibrary(h);
1901 rb_sys_fail("GetAdaptersAddresses");
1902 }
1903
1904 list = rb_ary_new();
1905 for (; adapters; adapters = adapters->Next) {
1906 ip_adapter_unicast_address_t *uni;
1907 ip_adapter_anycast_address_t *any;
1908 if (adapters->OperStatus != 1) /* 1 means IfOperStatusUp */
1909 continue;
1910 for (uni = adapters->FirstUnicastAddress; uni; uni = uni->Next) {
1911#ifndef INET6
1912 if (uni->Address.lpSockaddr->sa_family == AF_INET)
1913#else
1914 if (IS_IP_FAMILY(uni->Address.lpSockaddr->sa_family))
1915#endif
1916 rb_ary_push(list, sockaddr_obj(uni->Address.lpSockaddr, uni->Address.iSockaddrLength));
1917 }
1918 for (any = adapters->FirstAnycastAddress; any; any = any->Next) {
1919#ifndef INET6
1920 if (any->Address.lpSockaddr->sa_family == AF_INET)
1921#else
1922 if (IS_IP_FAMILY(any->Address.lpSockaddr->sa_family))
1923#endif
1924 rb_ary_push(list, sockaddr_obj(any->Address.lpSockaddr, any->Address.iSockaddrLength));
1925 }
1926 }
1927
1928 FreeLibrary(h);
1929 return list;
1930#endif
1931}
1932#else
1933#define socket_s_ip_address_list rb_f_notimplement
1934#endif
1935
1936void
1938{
1940
1941 /*
1942 * Document-class: Socket < BasicSocket
1943 *
1944 * Class +Socket+ provides access to the underlying operating system
1945 * socket implementations. It can be used to provide more operating system
1946 * specific functionality than the protocol-specific socket classes.
1947 *
1948 * The constants defined under Socket::Constants are also defined under
1949 * Socket. For example, Socket::AF_INET is usable as well as
1950 * Socket::Constants::AF_INET. See Socket::Constants for the list of
1951 * constants.
1952 *
1953 * === What's a socket?
1954 *
1955 * Sockets are endpoints of a bidirectional communication channel.
1956 * Sockets can communicate within a process, between processes on the same
1957 * machine or between different machines. There are many types of socket:
1958 * TCPSocket, UDPSocket or UNIXSocket for example.
1959 *
1960 * Sockets have their own vocabulary:
1961 *
1962 * *domain:*
1963 * The family of protocols:
1964 * * Socket::PF_INET
1965 * * Socket::PF_INET6
1966 * * Socket::PF_UNIX
1967 * * etc.
1968 *
1969 * *type:*
1970 * The type of communications between the two endpoints, typically
1971 * * Socket::SOCK_STREAM
1972 * * Socket::SOCK_DGRAM.
1973 *
1974 * *protocol:*
1975 * Typically _zero_.
1976 * This may be used to identify a variant of a protocol.
1977 *
1978 * *hostname:*
1979 * The identifier of a network interface:
1980 * * a string (hostname, IPv4 or IPv6 address or +broadcast+
1981 * which specifies a broadcast address)
1982 * * a zero-length string which specifies INADDR_ANY
1983 * * an integer (interpreted as binary address in host byte order).
1984 *
1985 * === Quick start
1986 *
1987 * Many of the classes, such as TCPSocket, UDPSocket or UNIXSocket,
1988 * ease the use of sockets comparatively to the equivalent C programming interface.
1989 *
1990 * Let's create an internet socket using the IPv4 protocol in a C-like manner:
1991 *
1992 * require 'socket'
1993 *
1994 * s = Socket.new Socket::AF_INET, Socket::SOCK_STREAM
1995 * s.connect Socket.pack_sockaddr_in(80, 'example.com')
1996 *
1997 * You could also use the TCPSocket class:
1998 *
1999 * s = TCPSocket.new 'example.com', 80
2000 *
2001 * A simple server might look like this:
2002 *
2003 * require 'socket'
2004 *
2005 * server = TCPServer.new 2000 # Server bound to port 2000
2006 *
2007 * loop do
2008 * client = server.accept # Wait for a client to connect
2009 * client.puts "Hello !"
2010 * client.puts "Time is #{Time.now}"
2011 * client.close
2012 * end
2013 *
2014 * A simple client may look like this:
2015 *
2016 * require 'socket'
2017 *
2018 * s = TCPSocket.new 'localhost', 2000
2019 *
2020 * while line = s.gets # Read lines from socket
2021 * puts line # and print them
2022 * end
2023 *
2024 * s.close # close socket when done
2025 *
2026 * === Exception Handling
2027 *
2028 * Ruby's Socket implementation raises exceptions based on the error
2029 * generated by the system dependent implementation. This is why the
2030 * methods are documented in a way that isolate Unix-based system
2031 * exceptions from Windows based exceptions. If more information on a
2032 * particular exception is needed, please refer to the Unix manual pages or
2033 * the Windows WinSock reference.
2034 *
2035 * === Convenience methods
2036 *
2037 * Although the general way to create socket is Socket.new,
2038 * there are several methods of socket creation for most cases.
2039 *
2040 * TCP client socket::
2041 * Socket.tcp, TCPSocket.open
2042 * TCP server socket::
2043 * Socket.tcp_server_loop, TCPServer.open
2044 * UNIX client socket::
2045 * Socket.unix, UNIXSocket.open
2046 * UNIX server socket::
2047 * Socket.unix_server_loop, UNIXServer.open
2048 *
2049 * === Documentation by
2050 *
2051 * * Zach Dennis
2052 * * Sam Roberts
2053 * * <em>Programming Ruby</em> from The Pragmatic Bookshelf.
2054 *
2055 * Much material in this documentation is taken with permission from
2056 * <em>Programming Ruby</em> from The Pragmatic Bookshelf.
2057 */
2059
2061
2062 rb_define_method(rb_cSocket, "initialize", sock_initialize, -1);
2063 rb_define_method(rb_cSocket, "connect", sock_connect, 1);
2064
2065 /* for ext/socket/lib/socket.rb use only: */
2067 "__connect_nonblock", sock_connect_nonblock, 2);
2068
2069 rb_define_method(rb_cSocket, "bind", sock_bind, 1);
2071 rb_define_method(rb_cSocket, "accept", sock_accept, 0);
2072
2073 /* for ext/socket/lib/socket.rb use only: */
2075 "__accept_nonblock", sock_accept_nonblock, 1);
2076
2077 rb_define_method(rb_cSocket, "sysaccept", sock_sysaccept, 0);
2078
2079 rb_define_method(rb_cSocket, "recvfrom", sock_recvfrom, -1);
2080
2081 /* for ext/socket/lib/socket.rb use only: */
2083 "__recvfrom_nonblock", sock_recvfrom_nonblock, 4);
2084
2088 rb_define_singleton_method(rb_cSocket, "gethostbyname", sock_s_gethostbyname, 1);
2089 rb_define_singleton_method(rb_cSocket, "gethostbyaddr", sock_s_gethostbyaddr, -1);
2090 rb_define_singleton_method(rb_cSocket, "getservbyname", sock_s_getservbyname, -1);
2091 rb_define_singleton_method(rb_cSocket, "getservbyport", sock_s_getservbyport, -1);
2092 rb_define_singleton_method(rb_cSocket, "getaddrinfo", sock_s_getaddrinfo, -1);
2093 rb_define_singleton_method(rb_cSocket, "getnameinfo", sock_s_getnameinfo, -1);
2094 rb_define_singleton_method(rb_cSocket, "sockaddr_in", sock_s_pack_sockaddr_in, 2);
2095 rb_define_singleton_method(rb_cSocket, "pack_sockaddr_in", sock_s_pack_sockaddr_in, 2);
2096 rb_define_singleton_method(rb_cSocket, "unpack_sockaddr_in", sock_s_unpack_sockaddr_in, 1);
2097#ifdef HAVE_SYS_UN_H
2098 rb_define_singleton_method(rb_cSocket, "sockaddr_un", sock_s_pack_sockaddr_un, 1);
2099 rb_define_singleton_method(rb_cSocket, "pack_sockaddr_un", sock_s_pack_sockaddr_un, 1);
2100 rb_define_singleton_method(rb_cSocket, "unpack_sockaddr_un", sock_s_unpack_sockaddr_un, 1);
2101#endif
2102
2104
2105#undef rb_intern
2106 sym_wait_writable = ID2SYM(rb_intern("wait_writable"));
2107}
int errno
#define AI_NUMERICHOST
Definition: addrinfo.h:98
#define AI_CANONNAME
Definition: addrinfo.h:97
#define NI_DGRAM
Definition: addrinfo.h:128
void rsock_init_basicsocket(void)
Definition: basicsocket.c:704
int rsock_family_arg(VALUE domain)
Definition: constants.c:42
int rsock_socktype_arg(VALUE type)
Definition: constants.c:49
struct RIMemo * ptr
Definition: debug.c:65
#define Next(p, e, enc)
Definition: dir.c:216
st_table * names
Definition: encoding.c:59
struct rb_encoding_entry * list
Definition: encoding.c:56
char str[HTML_ESCAPE_MAX_LEN+1]
Definition: escape.c:18
int socklen_t
Definition: getaddrinfo.c:83
VALUE rb_define_class(const char *, VALUE)
Defines a top-level class.
Definition: class.c:662
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition: eval.c:898
void rb_notimplement(void)
Definition: error.c:2714
void rb_syserr_fail(int e, const char *mesg)
Definition: error.c:2783
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2671
void rb_syserr_fail_str(int e, VALUE mesg)
Definition: error.c:2789
VALUE rb_eRangeError
Definition: error.c:928
VALUE rb_eTypeError
Definition: error.c:924
VALUE rb_eArgError
Definition: error.c:925
VALUE rb_rescue(VALUE(*)(VALUE), VALUE, VALUE(*)(VALUE, VALUE), VALUE)
An equivalent of rescue clause.
Definition: eval.c:1047
VALUE rb_ensure(VALUE(*)(VALUE), VALUE, VALUE(*)(VALUE), VALUE)
An equivalent to ensure clause.
Definition: eval.c:1115
void rb_sys_fail(const char *mesg)
Definition: error.c:2795
VALUE rb_obj_alloc(VALUE)
Allocates an instance of klass.
Definition: object.c:1895
void rb_readwrite_syserr_fail(enum rb_io_wait_readwrite writable, int n, const char *mesg)
Definition: io.c:12944
#define GetOpenFile(obj, fp)
Definition: io.h:127
void rb_io_set_nonblock(rb_io_t *fptr)
Definition: io.c:2782
int rsock_revlookup_flag(VALUE revlookup, int *norevlookup)
Definition: ipsocket.c:179
VALUE type(ANYARGS)
ANYARGS-ed function type.
Definition: cxxanyargs.hpp:39
const char * name
Definition: nkf.c:208
void rb_freeaddrinfo(struct rb_addrinfo *ai)
Definition: raddrinfo.c:396
VALUE rsock_addrinfo_new(struct sockaddr *addr, socklen_t len, int family, int socktype, int protocol, VALUE canonname, VALUE inspectname)
Definition: raddrinfo.c:910
struct rb_addrinfo * rsock_getaddrinfo(VALUE host, VALUE port, struct addrinfo *hints, int socktype_hack)
Definition: raddrinfo.c:576
VALUE rsock_make_hostent(VALUE host, struct rb_addrinfo *addr, VALUE(*ipaddr)(struct sockaddr *, socklen_t))
Definition: raddrinfo.c:816
VALUE rsock_make_ipaddr(struct sockaddr *addr, socklen_t addrlen)
Definition: raddrinfo.c:470
VALUE rsock_addrinfo_inspect_sockaddr(VALUE self)
Definition: raddrinfo.c:1641
VALUE rb_check_sockaddr_string_type(VALUE val)
Definition: raddrinfo.c:2626
int rb_getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct rb_addrinfo **res)
Definition: raddrinfo.c:309
struct rb_addrinfo * rsock_addrinfo(VALUE host, VALUE port, int family, int socktype, int flags)
Definition: raddrinfo.c:653
VALUE rsock_ipaddr(struct sockaddr *sockaddr, socklen_t sockaddrlen, int norevlookup)
Definition: raddrinfo.c:665
int rb_getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags)
Definition: raddrinfo.c:437
VALUE rsock_io_socket_addrinfo(VALUE io, struct sockaddr *addr, socklen_t len)
Definition: raddrinfo.c:2653
#define RARRAY_LEN(a)
#define rb_str_new2
#define NULL
#define rb_funcallv(recv, mid, argc, argv)
VALUE rb_str_resize(VALUE, long)
Definition: string.c:2709
use StringValue() instead")))
#define RSTRING_LEN(str)
#define _(args)
#define ALLOCA_N(type, n)
#define EISCONN
#define STRTOUL(str, endptr, base)
size_t strlen(const char *)
int strcmp(const char *, const char *)
void rb_define_private_method(VALUE, const char *, VALUE(*)(), int)
#define T_STRING
VALUE rb_assoc_new(VALUE, VALUE)
Definition: array.c:896
#define offsetof(TYPE, MEMBER)
__uint16_t uint16_t
int close(int __fildes)
#define PRIuSIZE
#define xfree
#define EINVAL
const VALUE VALUE obj
#define RSTRING_PTR(str)
const rb_iseq_t const char * error
#define xrealloc
#define ENAMETOOLONG
char * strncpy(char *__restrict__, const char *__restrict__, size_t)
int snprintf(char *__restrict__, size_t, const char *__restrict__,...) __attribute__((__format__(__printf__
#define rb_str_new(str, len)
#define NIL_P(v)
#define ID2SYM(x)
void rb_maygvl_fd_fix_cloexec(int fd)
Definition: io.c:245
char * strcpy(char *__restrict__, const char *__restrict__)
const char size_t n
#define MEMZERO(p, type, n)
unsigned long VALUE
VALUE rb_ary_push(VALUE, VALUE)
Definition: array.c:1195
void rb_update_max_fd(int fd)
Definition: io.c:218
int rb_gc_for_fd(int err)
Definition: io.c:953
#define RARRAY_ASET(a, i, v)
#define xmalloc
#define EINPROGRESS
uint32_t i
__inline__ const void *__restrict__ size_t len
#define INT2NUM(x)
#define NUM2INT(x)
void rb_define_singleton_method(VALUE, const char *, VALUE(*)(), int)
#define PRIsVALUE
void * memset(void *, int, size_t)
const char * s2
VALUE rb_ary_new(void)
Definition: array.c:723
#define rb_scan_args(argc, argvp, fmt,...)
#define rb_intern(str)
#define UNREACHABLE_RETURN(val)
void rb_fd_fix_cloexec(int fd)
Definition: io.c:268
struct rb_call_cache buf
#define Qnil
#define Qfalse
void rb_str_modify_expand(VALUE, long)
Definition: string.c:2122
void * memcpy(void *__restrict__, const void *__restrict__, size_t)
#define RB_TYPE_P(obj, type)
#define INT2FIX(i)
VALUE rb_check_array_type(VALUE)
Definition: array.c:909
#define RB_IO_WAIT_WRITABLE
const VALUE * argv
#define SYMBOL_P(x)
#define FIXNUM_P(f)
VALUE rb_sprintf(const char *,...) __attribute__((format(printf
VALUE rb_yield(VALUE)
Definition: vm_eval.c:1237
size_t st_index_t h
#define NUM2LONG(x)
void rb_define_method(VALUE, const char *, VALUE(*)(), int)
#define RARRAY_AREF(a, i)
#define rb_str_new4
#define LONG_LONG
double log(double)
VALUE rb_ary_entry(VALUE, long)
Definition: array.c:1512
#define StringValueCStr(v)
int gethostname(char *__name, size_t __len)
#define IS_IP_FAMILY(af)
Definition: rubysocket.h:162
#define SockAddrStringValueWithAddrinfo(v, rai_ret)
Definition: rubysocket.h:272
#define SockAddrStringValuePtr(v)
Definition: rubysocket.h:271
VALUE rsock_sockaddr_obj(struct sockaddr *addr, socklen_t len)
#define RSOCK_NONBLOCK_DEFAULT
Definition: rubysocket.h:35
@ RECV_SOCKET
Definition: rubysocket.h:344
#define RSTRING_SOCKLEN
Definition: rubysocket.h:130
socklen_t rsock_sockaddr_len(struct sockaddr *addr)
#define proto(p)
Definition: sdbm.h:60
void rsock_raise_socket_error(const char *reason, int error)
Definition: init.c:39
void rsock_make_fd_nonblock(int fd)
Definition: init.c:638
VALUE rsock_s_recvfrom_nonblock(VALUE sock, VALUE len, VALUE flg, VALUE str, VALUE ex, enum sock_recv_type from)
Definition: init.c:231
VALUE rb_eSocket
Definition: init.c:29
VALUE rsock_s_accept_nonblock(VALUE klass, VALUE ex, rb_io_t *fptr, struct sockaddr *sockaddr, socklen_t *len)
Definition: init.c:709
VALUE rsock_s_accept(VALUE klass, int fd, struct sockaddr *sockaddr, socklen_t *len)
Definition: init.c:751
int rsock_socket(int domain, int type, int proto)
Definition: init.c:491
int rsock_detect_cloexec(int fd)
Definition: init.c:412
VALUE rsock_init_sock(VALUE sock, int fd)
Definition: init.c:78
int rsock_do_not_reverse_lookup
Definition: init.c:35
VALUE rsock_s_recvfrom(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from)
Definition: init.c:169
void rsock_init_socket_init(void)
Definition: init.c:818
int rsock_connect(int fd, const struct sockaddr *sockaddr, int len, int socks)
Definition: init.c:607
VALUE rb_cSocket
Definition: init.c:26
VALUE rb_cBasicSocket
Definition: init.c:17
#define rsock_sock_s_socketpair
Definition: socket.c:317
void rsock_sys_fail_raddrinfo_or_sockaddr(const char *mesg, VALUE addr, VALUE rai)
Definition: socket.c:88
void Init_socket(void)
Definition: socket.c:1937
void rsock_sys_fail_host_port(const char *mesg, VALUE host, VALUE port)
Definition: socket.c:18
void rsock_sys_fail_raddrinfo(const char *mesg, VALUE rai)
Definition: socket.c:71
void rsock_syserr_fail_host_port(int err, const char *mesg, VALUE host, VALUE port)
Definition: socket.c:24
void rsock_syserr_fail_sockaddr(int err, const char *mesg, struct sockaddr *addr, socklen_t len)
Definition: socket.c:61
void rsock_sys_fail_path(const char *mesg, VALUE path)
Definition: socket.c:35
void rsock_syserr_fail_path(int err, const char *mesg, VALUE path)
Definition: socket.c:41
#define socket_s_ip_address_list
Definition: socket.c:1933
void rsock_syserr_fail_raddrinfo(int err, const char *mesg, VALUE rai)
Definition: socket.c:77
#define sock_gethostname
Definition: socket.c:941
void rsock_sys_fail_sockaddr(const char *mesg, struct sockaddr *addr, socklen_t len)
Definition: socket.c:55
void rsock_syserr_fail_raddrinfo_or_sockaddr(int err, const char *mesg, VALUE addr, VALUE rai)
Definition: socket.c:94
VALUE rsock_sock_listen(VALUE sock, VALUE log)
Definition: socket.c:653
#define VALIDATE_SOCKLEN(addr, len)
Definition: sockport.h:16
#define PF_UNSPEC
Definition: sockport.h:105
#define AF_UNSPEC
Definition: sockport.h:101
size_t ai_addrlen
Definition: addrinfo.h:136
struct sockaddr * ai_addr
Definition: addrinfo.h:138
char * ai_canonname
Definition: addrinfo.h:137
int ai_socktype
Definition: addrinfo.h:134
int ai_protocol
Definition: addrinfo.h:135
struct addrinfo * ai_next
Definition: addrinfo.h:139
int ai_family
Definition: addrinfo.h:133
Definition: win32.h:240
struct sockaddr * ifa_addr
Definition: win32.h:244
char * ifa_name
Definition: win32.h:242
struct ifaddrs * ifa_next
Definition: win32.h:241
struct addrinfo * ai
Definition: rubysocket.h:291
Definition: io.h:66
int fd
Definition: io.h:68
struct sockaddr addr
Definition: rubysocket.h:193
int rb_w32_map_errno(DWORD)
Definition: win32.c:273
void freeifaddrs(struct ifaddrs *)
Definition: win32.c:4206
int socketpair(int, int, int, int *)
Definition: win32.c:4052
int getifaddrs(struct ifaddrs **)
Definition: win32.c:4119
int ioctl(int, int,...)
Definition: win32.c:2841
IUnknown DWORD
Definition: win32ole.c:33