Ruby: ext/socket/socket.c Source File

Ruby 3.0.5p211 (2022-11-24 revision ba5cf0f7c52d4d35cc6a173c89eda98ceffa2dcf)

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