Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

Ruby Programming
Previous Page Home Next Page

Socket-Level Access

Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents. Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. The socket library provides specific classes for handling the common transports as well as a generic interface for handling the rest. All functionality in the socket library is accessible through a single extension library. Access it using

require 'socket'

Sockets have their own vocabulary:

domain
The family of protocols that will be used as the transport mechanism. These values are constants such as PF_INET, PF_UNIX, PF_X25, and so on.
type
The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
protocol
Typically zero, this may be used to identify a variant of a protocol within a domain and type.
hostName
The identifier of a network interface:
  • a string, which can be a host name, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation,
  • the string ``<broadcast>'', which specifies an INADDR_BROADCAST address,
  • a zero-length string, which specifies INADDR_ANY, or
  • an Integer, interpreted as a binary address in host byte order.
port
(sometimes called service) Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.

Sockets are children of class IO. Once a socket has been successfully opened, the conventional I/O methods may be used. However, greater efficiency is sometimes obtained by using socket-specific methods. As with other I/O classes, socket I/O blocks by default. The hierarchy of the socket classes is shown in Figure 26.1 on page 471.

For more information on the use of sockets, see your operating system documentation. You'll also find a comprehensive treatment in W. Richard Stevens, Unix Network Programming, Volumes 1 and 2 .

class BasicSocket
Parent: IO
Version: 1.6

Index:

do_not_reverse_lookup do_not_reverse_lookup= lookup_order lookup_order= close_read close_write getpeername getsockname getsockopt recv send setsockopt shutdown


BasicSocket is an abstract base class for all other socket classes.

This class and its subclasses often manipulate addresses using something called a struct sockaddr, which is effectively an opaque binary string.[In reality, it maps onto the underlying C-language struct sockaddr set of structures, documented in the man pages and in the books by Stevens.]

class methods
do_not_reverse_lookup BasicSocket.do_not_reverse_lookup -> true or false

Returns the value of the global reverse lookup flag. If set to true, queries on remote addresses will return the numeric address but not the host name.

do_not_reverse_lookup= BasicSocket.do_not_reverse_lookup = true or false

Sets the global reverse lookup flag.

lookup_order BasicSocket.lookup_order -> aFixnum

Returns the global address lookup order, one of:

Order Families Searched
LOOKUP_UNSP AF_UNSPEC
LOOKUP_INET AF_INET, AF_INET6, AF_UNSPEC
LOOKUP_INET6 AF_INET6, AF_INET, AF_UNSPEC

lookup_order= BasicSocket.lookup_order = aFixnum

Sets the global address lookup order.

instance methods
close_read aSession.close_read -> nil

Closes the readable connection on this socket.

close_write aSession.close_write -> nil

Closes the writable connection on this socket.

getpeername aSession.getpeername -> aString

Returns the struct sockaddr structure associated with the other end of this socket connection.

getsockname aSession.getsockname -> aString

Returns the struct sockaddr structure associated with aSession.

getsockopt aSession.getsockopt( level, optname ) -> aString

Returns the value of the specified option.

recv aSession.recv( len, [, flags ] ) -> aString

Receives up to len bytes from aSession.

send aSession.send( aString, flags, [, to ] ) -> aFixnum

Sends aString over aSession. If specified, to is a struct sockaddr specifying the recipient address. flags are the sum or one or more of the MSG_ options (listed on page 478). Returns the number of characters sent.

setsockopt aSession.setsockopt( level, optname, optval ) -> 0

Sets a socket option. level is one of the socket-level options (listed on page 478). optname and optval are protocol specific---see your system documentation for details.

shutdown aSession.shutdown( how=2 ) -> 0

Shuts down the receive (how == 0), or send (how == 1), or both (how == 2), parts of this socket.

class IPSocket
Parent: BasicSocket
Version: 1.6

Index:

getaddress addr peeraddr


Class IPSocket is a base class for sockets using IP as their transport. TCPSocket and UDPSocket are based on this class.

class methods
getaddress IPSocket.getaddress( hostName ) -> aString

Returns the dotted-quad IP address of hostName.

a = IPSocket.getaddress('www.ruby-lang.org')
a "210.251.121.214"

instance methods
addr aSession.addr -> anArray

Returns the domain, port, name, and IP address of aSession as a four-element array. The name will be returned as an address if the do_not_reverse_lookup flag is true.

u = UDPSocket.new
u.bind('localhost', 8765)
u.addr ["AF_INET", 8765, "localhost", "127.0.0.1"]
BasicSocket.do_not_reverse_lookup = true
u.addr ["AF_INET", 8765, "127.0.0.1", "127.0.0.1"]

peeraddr aSession.peeraddr -> anArray

Returns the domain, port, name, and IP address of the peer.

class TCPSocket
Parent: IPSocket
Version: 1.6

Index:

gethostbyname new open recvfrom


t = TCPSocket.new('localhost', 'ftp')
t.gets "220 zip.local.thomases.com FTP server (Version 6.5/OpenBSD, linux port 0.3.2) ready.\r\n"
t.close nil

class methods
gethostbyname TCPSocket.gethostbyname( hostName ) -> anArray

Looks up hostName and returns its canonical name, an array containing any aliases, the address type (AF_INET), and the dotted-quad IP address.

a = TCPSocket.gethostbyname('ns.pragprog.com')
a ["pragprog.com", [], 2, "216.87.136.211"]

new TCPSocket.new( hostName, port ) -> aSession

Opens a TCP connection to hostName on the port.

open TCPSocket.open( hostName, port ) -> aSession

Synonym for TCPSocket.new.

instance methods
recvfrom aSession.recvfrom( len [, flags ] ) -> anArray

Receives up to len bytes on the connection. flags is zero or more of the MSG_ options (listed on page 478). Returns a two-element array. The first element is the received data, the second is an array containing information about the peer.

t = TCPSocket.new('localhost', 'ftp')
data = t.recvfrom(30)
data

class SOCKSSocket
Parent: TCPSocket
Version: 1.6

Index:

new open close


Class SOCKSSocket supports connections based on the SOCKS protocol.
class methods
new SOCKSSocket.new( hostName, port ) -> aSession

Opens a SOCKS connection to port on hostName.

open SOCKSSocket.open( hostName, port ) -> aSession

Synonym for SOCKSSocket.new.

instance methods
close aSession.close -> nil

Closes this SOCKS connection.

class TCPServer
Parent: TCPSocket
Version: 1.6

Index:

new open accept


A TCPServer accepts incoming TCP connections. Here is a Web server that listens on a given port and returns the time.

require 'socket'
port = (ARGV[0] || 80).to_i
server = TCPServer.new('localhost', port)
while (session = server.accept)
  puts "Request: #{session.gets}"
  session.print "HTTP/1.1 200/OK\r\nContent-type: text/html\r\n\r\n"
  session.print "<html><body><h1>#{Time.now}</h1></body></html>\r\n"
  session.close
end

class methods
new TCPServer.new( [ hostName,] port ) -> aSession
Creates a new socket on the given interface (identified by hostName and port). If hostName is omitted, the server will listen on all interfaces on the current host (equivalent to an address of 0.0.0.0).

open TCPServer.open( [ hostName,] port ) -> aSession

Synonym for TCPServer.new.

instance methods
accept aSession.accept -> aTCPSocket

Waits for a connection on aSession, and returns a new TCPSocket connected to the caller. See the example on page 474.

class UDPSocket
Parent: IPSocket
Version: 1.6

Index:

new open bind connect recvfrom send


UDP sockets send and receive datagrams. In order to receive data, a socket must be bound to a particular port. You have two choices when sending data: you can connect to a remote UDP socket and thereafter send datagrams to that port, or you can specify a host and port for use with every packet you send. This example is a UDP server that prints the message it receives. It is called by both connectionless and connection-based clients.

require 'socket'

$port = 4321

sThread = Thread.start do     # run server in a thread   server = UDPSocket.open   server.bind(nil, $port)   2.times { p server.recvfrom(64) } end

# Ad-hoc client UDPSocket.open.send("ad hoc", 0, 'localhost', $port)

# Connection based client sock = UDPSocket.open sock.connect('localhost', $port) sock.send("connection-based", 0) sThread.join
produces:
["ad hoc", ["AF_INET", 33224, "localhost", "127.0.0.1"]]
["connection-based", ["AF_INET", 33225, "localhost", "127.0.0.1"]]

class methods
new UDPSocket.new( family = AF_INET ) -> aSession

Creates an endpoint for UDP communications, optionally specifying the address family.

open UDPSocket.open( family = AF_INET ) -> aSession

Synonym for UDPSocket.new.

instance methods
bind aSession.bind( hostName, port ) -> 0

Associates the local end of the UDP connection with a given hostName and port. Must be used by servers to establish an accessible endpoint.

connect aSession.connect( hostName, port ) -> 0

Creates a connection to the given hostName and port. Subsequent UDPSocket#send requests that don't override the recipient will use this connection. Multiple connect requests may be issued on aSession: the most recent will be used by send.

recvfrom aSession.recvfrom( len [, flags ] ) -> anArray

Receives up to len bytes from aSession. flags is zero or more of the MSG_ options (listed on page 478). The result is a two-element array containing the received data and information on the sender. See the example on page 475.

send aSession.send( aString, flags ) -> aFixnum
aSession.send( aString, flags, hostName, port ) -> aFixnum

The two-parameter form sends aString on an existing connection. The four-parameter form sends aString to port on hostName.

class UNIXSocket
Parent: BasicSocket
Version: 1.6

Index:

new open addr path peeraddr recvfrom


Class UNIXSocket supports interprocess communications using the Unix domain protocol. Although the underlying protocol supports both datagram and stream connections, the Ruby library provides only a stream-based connection.

require 'socket'

$path = "/tmp/sample"

sThread = Thread.start do        # run server in a thread   sock = UNIXServer.open($path)   s1 = sock.accept   p s1.recvfrom(124) end

client = UNIXSocket.open($path) client.send("hello", 0) client.close

sThread.join
produces:
["hello", ["AF_UNIX", ""]]

class methods
new UNIXSocket.new( path ) -> aSession

Opens a new domain socket on path, which must be a pathname.

open UNIXSocket.open( path ) -> aSession

Synonym for UNIXSocket.new.

instance methods
addr aSession.addr -> anArray

Returns the address family and path of this socket.

path aSession.path -> aString

Returns the path of this domain socket.

peeraddr aSession.peeraddr -> anArray

Returns the address family and path of the server end of the connection.

recvfrom aSession.recvfrom( len [, flags ] ) -> anArray

Receives up to len bytes from aSession. flags is zero or more of the MSG_ options (listed on page 478). The first element of the returned array is the received data, and the second contains (minimal) information on the sender.

class UNIXServer
Parent: UNIXSocket
Version: 1.6

Index:

new open accept


Class UNIXServer provides a simple Unix domain socket server. See UNIXSocket for example code.

class methods
new UNIXServer.new( path ) -> aSession

Creates a server on the given path. The corresponding file must not exist at the time of the call.

open UNIXServer.open( path ) -> aSession

Synonym for UNIXServer.new.

instance methods
accept aSession.accept -> aUnixSocket

Waits for a connection on the server socket and returns a new socket object for that connection. See the example for UNIXSocket on page 476.

class Socket
Parent: BasicSocket
Version: 1.6

Index:

for_fd getaddrinfo gethostbyaddr gethostbyname gethostname getnameinfo getservbyname new open pair socketpair accept bind connect listen recvfrom


Class Socket provides access to the underlying operating system socket implementation. It can be used to provide more operating system-specific functionality than the protocol-specific socket classes, but at the expense of greater complexity. In particular, the class handles addresses using struct sockaddr structures packed into Ruby strings, which can be a joy to manipulate.

constants

Class Socket defines constants for use throughout the socket library. Individual constants are available only on architectures that support the related facility.

Types:

SOCK_DGRAM, SOCK_PACKET, SOCK_RAW, SOCK_RDM, SOCK_SEQPACKET, SOCK_STREAM.

Protocol families:

PF_APPLETALK, PF_AX25, PF_INET6, PF_INET, PF_IPX, PF_UNIX, PF_UNSPEC.

Address families:

AF_APPLETALK, AF_AX25, AF_INET6, AF_INET, AF_IPX, AF_UNIX, AF_UNSPEC.

Lookup-order options:

LOOKUP_INET6, LOOKUP_INET, LOOKUP_UNSPEC.

Send/receive options:

MSG_DONTROUTE, MSG_OOB, MSG_PEEK.

Socket-level options:

SOL_ATALK, SOL_AX25, SOL_IPX, SOL_IP, SOL_SOCKET, SOL_TCP, SOL_UDP.

Socket options:

SO_BROADCAST, SO_DEBUG, SO_DONTROUTE, SO_ERROR, SO_KEEPALIVE, SO_LINGER, SO_NO_CHECK, SO_OOBINLINE, SO_PRIORITY, SO_RCVBUF, SO_REUSEADDR, SO_SNDBUF, SO_TYPE.

QOS options:

SOPRI_BACKGROUND, SOPRI_INTERACTIVE, SOPRI_NORMAL.

Multicast options:

IP_ADD_MEMBERSHIP, IP_DEFAULT_MULTICAST_LOOP, IP_DEFAULT_MULTICAST_TTL, IP_MAX_MEMBERSHIPS, IP_MULTICAST_IF, IP_MULTICAST_LOOP, IP_MULTICAST_TTL.

TCP options:

TCP_MAXSEG, TCP_NODELAY.

getaddrinfo error codes:

EAI_ADDRFAMILY, EAI_AGAIN, EAI_BADFLAGS, EAI_BADHINTS, EAI_FAIL, EAI_FAMILY, EAI_MAX, EAI_MEMORY, EAI_NODATA, EAI_NONAME, EAI_PROTOCOL, EAI_SERVICE, EAI_SOCKTYPE, EAI_SYSTEM.

ai_flags values:

AI_ALL, AI_CANONNAME, AI_MASK, AI_NUMERICHOST, AI_PASSIVE, AI_V4MAPPED_CFG.

class methods
for_fd Socket.for_fd( anFD ) -> aSession

Wraps an already open file descriptor into a socket object.

getaddrinfo Socket.getaddrinfo( hostName, port,
[ family [ socktype [ protocol [ flags ] ] ] ] ) -> anArray

Returns an array of arrays describing the given host and port (optionally qualified as shown). Each subarray contains the address family, port number, host name, host IP address, protocol family, socket type, and protocol.

for line in Socket.getaddrinfo('www.microsoft.com', 'http')
  puts line.join(", ")
end
produces:
AF_INET, 80, microsoft.net, 207.46.130.149, 2, 1, 6
AF_INET, 80, microsoft.net, 207.46.131.137, 2, 1, 6
AF_INET, 80, microsoft.com, 207.46.230.218, 2, 1, 6
AF_INET, 80, microsoft.com, 207.46.230.219, 2, 1, 6
AF_INET, 80, microsoft.net, 207.46.130.14, 2, 1, 6

gethostbyaddr Socket.gethostbyaddr( addr, type=AF_INET ) -> anArray
Returns the host name, address family, and sockaddr component for the given address.

a = Socket.gethostbyname("216.87.136.211")
res = Socket.gethostbyaddr(a[3], a[2])
res.join(', ') "pragprog.com, , 2, \330W\210\323"

gethostbyname Socket.gethostbyname( hostName ) -> anArray

Returns a four-element array containing the canonical host name, a subarray of host aliases, the address family, and the address portion of the sockaddr structure.

a = Socket.gethostbyname("216.87.136.211")
a.join(', ') "pragprog.com, , 2, \330W\210\323"

gethostname aSession.gethostname -> aString

Returns the name of the current host.

getnameinfo Socket.getnameinfo( addr [, flags ] ) -> anArray

Looks up the given address, which may be either a string containing a sockaddr or a three- or four-element array. If sockaddr is an array, it should contain the string address family, the port (or nil), and the host name or IP address. If a fourth element is present and not nil, it will be used as the host name. Returns a canonical hostname (or address) and port number as an array.

a = Socket.getnameinfo(["AF_INET", '23', 'www.ruby-lang.org'])
a ["helium.ruby-lang.org", "telnet"]

getservbyname Socket.getservbyname( service, proto='tcp' ) -> aFixnum

Returns the port corresponding to the given service and protocol.

Socket.getservbyname("telnet") 23

new Socket.new( domain, type, protocol ) -> aSession

Creates a socket using the given parameters.

open Socket.open( domain, type, protocol ) -> aSession

Synonym for Socket.new.

pair Socket.pair( domain, type, protocol ) -> anArray

Returns a pair of connected, anonymous sockets of the given domain, type, and protocol.

socketpair Socket.socketpair( domain, type, protocol ) -> anArray

Synonym for Socket.pair.

instance methods
accept aSession.accept -> anArray

Accepts an incoming connection returning an array containing a new Socket object and a string holding the struct sockaddr information about the caller.

bind aSession.bind( sockaddr ) -> 0

Binds to the given struct sockaddr, contained in a string.

connect aSession.connect( sockaddr ) -> 0

Connects to the given struct sockaddr, contained in a string.

listen aSession.listen( aFixnum ) -> 0

Listens for connections, using the specified aFixnum as the backlog.

recvfrom aSession.recvfrom( len [, flags ] ) -> anArray

Receives up to len bytes from aSession. flags is zero or more of the MSG_ options. The first element of the result is the data received. The second element contains protocol-specific information on the sender.

Ruby Programming
Previous Page Home Next Page

 
 
  Published under the terms of the Open Publication License Design by Interspire