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