/socket.wiki
Unknown | 969 lines | 750 code | 219 blank | 0 comment | 0 complexity | f62a93eb9d968ac82af55b0f8dc3383f MD5 | raw file
1[[tags:egg net]] 2 3== socket 4 5'''socket''' provides an interface to the BSD socket API. For a somewhat higher-level interface, see the [[/egg/tcp6|tcp6]] and [[/egg/udp6|udp6]] extensions. 6 7== Overview 8 9This extension provides a comprehensive interface to BSD sockets, 10including socket creation, client and server setup, data transfer, i/o 11ports, forward and reverse address resolution, socket options, and 12socket-related integer constants. It supports both IPv4 and IPv6, 13as well as UNIX sockets. 14 15All socket operations block only the calling thread; other threads can 16continue to run, even on Windows platforms. 17 18[[toc:]] 19 20== Socket interface 21 22=== Socket creation 23 24<record>socket</record><br> 25<procedure>(socket family type #!optional (protocol 0))</procedure><br> 26<procedure>(socket? so)</procedure><br> 27<procedure>(socket-fileno so)</procedure><br> 28<procedure>(socket-family so)</procedure><br> 29<procedure>(socket-type so)</procedure><br> 30<procedure>(socket-protocol so)</procedure><br> 31 32Socket objects. You construct a socket using the {{socket}} procedure, 33passing an address family {{af/*}} constant for FAMILY (IPv4, IPv6) and a 34socket type {{sock/*}} constant for socket TYPE (TCP, UDP). PROTOCOL 35should almost always be zero, unless you are creating raw sockets; it is 36implicit in the socket type. Sockets take up a file descriptor in the 37system until closed, which may or may not happen automatically on error. 38All sockets are created in non-blocking mode. 39 40Accessors: 41 42; {{fileno}} : The socket's file descriptor. 43; {{family}} : The socket family, an integer constant. 44; {{type}} : The socket type, an integer constant. 45; {{protocol}} : The socket protocol, an integer constant. 46 47Note that sockets are also implicitly created by {{socket-connect/ai}} 48and {{socket-accept}}. 49 50Example: 51 52 (socket af/inet sock/stream) 53 ; => #<socket fd:19 af/inet sock/stream> 54 (socket af/inet6 sock/dgram) 55 ; => #<socket fd:20 af/inet6 sock/dgram> 56 57<constant>af/inet</constant><br> 58<constant>af/inet6</constant><br> 59<constant>af/unix</constant><br> 60<constant>af/unspec</constant><br> 61<procedure>(integer->address-family int)</procedure> 62<procedure>(address-family->integer sym)</procedure> 63 64Address family constants for socket creation. It is possible to 65convert between integer constants and symbols using the provided 66procedures, but this is just for debugging convenience; the API 67requires integer constants. 68 69<constant>sock/stream</constant><br> 70<constant>sock/dgram</constant><br> 71<constant>sock/raw</constant><br> 72<procedure>(integer->socket-type int)</procedure> 73<procedure>(socket-type->integer sym)</procedure> 74 75Socket type constants for socket creation. 76 77<constant>ipproto/tcp</constant><br> 78<constant>ipproto/udp</constant><br> 79<procedure>(integer->protocol-type int)</procedure> 80<procedure>(protocol-type->integer sym)</procedure> 81 82Protocol constants for socket creation. 83 84=== Socket addresses 85 86<record>sockaddr</record><br> 87<procedure>(sockaddr? sa)</procedure><br> 88<procedure>(sockaddr-family sa)</procedure><br> 89<procedure>(sockaddr-address sa)</procedure><br> 90<procedure>(sockaddr-port sa)</procedure><br> 91<procedure>(sockaddr-path sa)</procedure><br> 92<procedure>(sockaddr->string sa)</procedure><br> 93 94The socket address object. {{sockaddr}} is used throughout 95the BSD sockets API to represent the address of a local or remote 96socket endpoint. 97 98The most convenient constructor for Internet socket addresses is 99{{inet-address}}. The fundamental Internet socket address constructor 100is {{address-information}}, which is more powerful but also more 101complex to use. For UNIX sockets, use {{unix-address}}. 102 103Socket address object accessors are: 104 105; {{family}} : returns the socket address family as an integer constant, e.g. {{af/inet}}. 106; {{address}} : returns the address of a socket as a string (for Internet sockets, this is the IP address). 107; {{port}} : returns the socket port for Internet sockets; it is an error to call it on another type of socket. 108; {{path}} : returns the pathname for UNIX sockets, or an error for other socket types. 109; {{->string}} : returns a compact representation of the socket address as a string. For Internet sockets, it returns "address" when port is 0; otherwise, it returns "address:port" for IPv4 addresses and "[address]:port" for IPv6 addresses. 110 111<procedure>(inet-address addr port)</procedure> 112 113Returns a {{sockaddr}} object constructed from IP address ADDR (a 114string) and port PORT (a number or numeric string). If the address 115or port input is invalid, an error is raised. 116 117If ADDR is {{#f}}, the unspecified address is used ("::" or "0.0.0.0"). 118If PORT is {{#f}}, the unspecified port is used (integer 0). 119It is an error for both ADDR and PORT to be unspecified. 120 121Note that when IPv6 is preferred on your system, the unspecified 122address {{#f}} is typically "::" and the resulting object will be of 123family {{af/inet6}}. This may not be what you want, so it is a good 124idea to specify which unspecified address (yes, really) you mean -- 125"::" or "0.0.0.0" -- in lieu of {{#f}}. 126 127<procedure>(unix-address PATH)</procedure> 128 129Returns a {{sockaddr}} object constructed from the pathname PATH, 130suitable for use with a socket in address family {{af/unix}}. 131Throws an error if UNIX sockets are not supported on your platform. 132 133=== Address resolution 134 135<procedure>(address-information node service #!key family (type sock/stream) protocol flags)</procedure><br> 136<constant>ai/numerichost</constant><br> 137<constant>ai/passive</constant><br> 138<constant>ai/canonname</constant><br> 139 140Looks up node name and service name and translates them to numeric 141values. Returns a list of {{addrinfo}} objects, each of which contains 142a socket address ({{sockaddr}} object) suitable for use in socket calls 143such as {{socket-bind}} and {{socket-connect}}. 144 145NODE is either a node name (string) or IP address (string). 146SERVICE may be a string representing a service name or port number, or 147an integer. If NODE is {{#f}}, it is treated as the loopback address; 148however, if {{ai/passive}} is set it is treated as the unspecified 149address. If SERVICE is {{#f}}, it is treated as unspecified (0). 150 151Keyword arguments accept numeric constants and restrict the returned addresses accordingly: 152 153; {{family:}} : Address family, either {{af/inet}} or {{af/inet6}}, defaulting to {{#f}}. If {{#f}}, both IPv6 and IPv4 addresses may be returned, depending on your system's configuration and IP stack. 154; {{type:}} : Socket type; usually {{sock/stream}} or {{sock/dgram}}, defaulting to {{sock/stream}}. Can be {{#f}}, but results may vary between systems, so it is safer to specify one. See examples. 155; {{protocol:}} : Protocol type, usually {{#f}}. Can also be {{ipproto/tcp}} or {{ipproto/udp}}; however, some systems (such as Windows) do not construct a proper socket address when {{type:}} is unspecified, so it is safer to just provide a value for {{type:}} and leave this as {{#f}}. 156 157The behavior of {{address-information}} can be influenced by the value 158of {{flags:}}, which should be the {{bitwise-ior}} (or simply {{+}}) of any 159of the following constants: 160 161; {{ai/numerichost}} : The host is an IP address string; do not attempt to resolve it. 162; {{ai/passive}} : The socket address is intended to be used in a call to bind(). The only difference is that an address of {{#f}} is translated into the unspecified address "::" or "0.0.0.0", rather than the loopback address. 163; {{ai/canonname}} : Include the canonical (usually FQDN) hostname in the {{addrinfo}} object. If not provided, that field will be {{#f}}. 164 165Examples: 166 167 (address-information "localhost" "http") 168 ; => (#<addrinfo "[::1]:80" af/inet6 sock/stream ipproto/tcp> 169 #<addrinfo "[fe80::1%lo0]:80" af/inet6 sock/stream ipproto/tcp> 170 #<addrinfo "127.0.0.1:80" af/inet sock/stream ipproto/tcp>) 171 (address-information "127.0.0.1" 53 type: sock/dgram) 172 ; => (#<addrinfo "127.0.0.1:53" af/inet sock/stream ipproto/udp>) 173 (address-information "he.net" 80) 174 ; => (#<addrinfo "[2001:470:0:76::2]:80" af/inet6 sock/stream ipproto/tcp> 175 #<addrinfo "216.218.186.2:80" af/inet sock/stream ipproto/tcp>) 176 (address-information "he.net" 80 type: #f) 177 ; Possible response on UNIX -- return both TCP and UDP addresses. 178 ; Might also just return TCP. 179 ; => (#<addrinfo "[2001:470:0:76::2]:80" af/inet6 sock/dgram ipproto/udp> 180 #<addrinfo "[2001:470:0:76::2]:80" af/inet6 sock/stream ipproto/tcp> 181 #<addrinfo "216.218.186.2:80" af/inet sock/dgram ipproto/udp> 182 #<addrinfo "216.218.186.2:80" af/inet sock/stream ipproto/tcp>) 183 ; Possible response on Windows -- socket addresses are not valid for use 184 ; => (#<addrinfo "[2001:470:0:76::2]:80" af/inet6 0 0> 185 #<addrinfo "216.218.186.2:80" af/inet 0 0>) 186 (address-information #f "http") 187 ; => (#<addrinfo "[::1]:80" af/inet6 sock/stream ipproto/tcp> 188 #<addrinfo "127.0.0.1:80" af/inet sock/stream ipproto/tcp>) 189 (address-information #f "http" flags: ai/passive) 190 ; => (#<addrinfo "[::]:80" af/inet6 sock/stream ipproto/tcp> 191 #<addrinfo "0.0.0.0:80" af/inet sock/stream ipproto/tcp>) 192 ; As an example of inconsistent per-platform behavior, note that 193 ; recent Ubuntu among others returns the above in reverse order. 194 (address-information "allie" 0 flags: ai/canonname) 195 ; => (#<addrinfo "192.168.1.7" af/inet sock/stream ipproto/tcp 196 canonical: "allie.xorinia.dim">) 197 (address-information #f #f) 198 ; => () 199 200<record>addrinfo</record> 201<procedure>(addrinfo? ai)</procedure> 202<procedure>(addrinfo-family ai)</procedure> 203<procedure>(addrinfo-socktype ai)</procedure> 204<procedure>(addrinfo-protocol ai)</procedure> 205<procedure>(addrinfo-address ai)</procedure> 206<procedure>(addrinfo-canonname ai)</procedure> 207<procedure>(addrinfo-flags ai)</procedure> 208 209Address information record returned by {{address-information}}. 210 211* {{address}} is the {{sockaddr}} socket address object; 212* {{family}}, {{socktype}} and {{protocol}} are numeric constants in the {{af/}}, {{sock/}} and {{ipproto/}} families respectively; 213* {{canonname}} is the canonical (FQDN) name of this host and is present only if the {{ai/canonname}} flag was used; otherwise {{#f}}; 214* {{flags}} is the bitwise OR of {{ai/}} flags used when constructing this object. The system may set certain flags itself so this is probably not reliably useful. 215 216<procedure>(name-information saddr #!optional (flags 0))</procedure><br> 217<constant>ni/numerichost</constant><br> 218<constant>ni/numericserv</constant><br> 219<constant>ni/dgram</constant><br> 220<constant>ni/namereqd</constant><br> 221<constant>ni/nofqdn</constant><br> 222 223Given a socket address object SADDR, performs a reverse-lookup to 224obtain the node and service names, returning them as the pair 225{{("node" . "service")}}. If hostname lookup fails, the numeric 226representation of the address is returned as a string. If service 227number lookup fails, it is returned as an integer. 228 229The socket address object is usually constructed with {{inet-address}} 230or obtained from a socket call, e.g. {{socket-peer-name}}. As a 231convenience in socket 0.2.1 and later, if {{SADDR}} is a string, it is 232converted to a socket address object with {{(inet-address SADDR #f)}}. 233 234The behavior of {{name-information}} can be influenced by FLAGS. FLAGS 235may be the {{bitwise-ior}} (or simply {{+}}) of the following 236constants: 237 238; {{ni/numerichost}} : Do not resolve the node address to a name; instead, return the canonical string representation of the address, as in {{inet_ntop()}}. {{(sockaddr-address saddr)}} returns the same representation. 239; {{ni/numericserv}} : Do not attempt to resolve the service number to a name. 240; {{ni/namereqd}} : If hostname lookup fails, raise an error. 241; {{ni/nofqdn}} : Return only the local part of the hostname for local hosts. 242; {{ni/dgram}} : Look up the service as a datagram service. A few service names may differ between TCP and UDP. 243 244Examples: 245 246 (name-information (inet-address "127.0.0.1" 80)) 247 ; => ("localhost" . "http") 248 (name-information (inet-address "::1" 80)) 249 ; => ("localhost" . "http") 250 (name-information (inet-address "::1" #f)) 251 ; => ("localhost" . 0) 252 (name-information "::1") 253 ; => ("localhost" . 0) 254 (name-information (inet-address "::1" 80) ni/numerichost) 255 ; => ("::1" . "http") 256 (name-information (inet-address "::1" 80) (+ ni/numerichost ni/numericserv)) 257 ; => ("::1" . 80) 258 (name-information (inet-address "127.0.0.2" 80)) 259 ; => ("127.0.0.2" . "http") 260 (name-information (inet-address "127.0.0.2" 80) ni/namereqd) 261 ; => error: nodename nor servname provided, or not known 262 (name-information (inet-address "2001:470:0:64::2" 80) ni/numericserv) 263 ; => ("ipv6.he.net" . 80) 264 (name-information (socket-peer-name s)) ;; s being an accept()ed socket 265 ; => ("taco.universe12.dim" . 31828) 266 267=== Setup and teardown 268 269<procedure>(socket-connect so saddr)</procedure><br> 270<procedure>(socket-connect/ai ais)</procedure><br> 271 272{{socket-connect}} connects to the remote socket address SADDR over 273the socket SO. Upon completion, SO will be connected; on connection 274failure an error is thrown. The return value is unspecified. This is 275a non-blocking operation; other SRFI-18 threads can continue to run. 276 277If connection fails due to refusal, network down, unreachable host or 278system enforced timeout, it raises a "transient" error of type {{(exn 279i/o net transient)}}, signalling the connection can be retried later 280if desired. A connection may also raise an {{(exn i/o net timeout)}} 281error after {{(socket-connect-timeout)}} milliseconds. If a fatal error 282occurs, it raises an error of type {{(exn i/o net)}}, like all other 283socket procedures. 284 285{{socket-connect/ai}} connects to the addresses in the {{addrinfo}} 286list AIS sequentially until the connection succeeds or there are no 287more addresses. If a fatal error occurs while connecting, it aborts 288immediately; but transient or timeout errors cause it to try the next 289address. If all attempts fail, the error raised is that of the last 290attempt. On success, the return value is a fresh connected socket of 291the appropriate family and type. 292 293Examples: 294 ;; Connect to localhost:22 over IPv4. 295 (define so (socket af/inet sock/stream)) 296 (socket-connect so (inet-address "127.0.0.1" 22)) 297 298 ;; Connect to localhost:22 over IPv6. 299 (define so (socket af/inet6 sock/stream)) 300 (socket-connect so (inet-address "::1" 22)) 301 302 ;; Connect to localhost:22 over IPv4 and return the connected socket. 303 (socket-connect/ai 304 (address-information "localhost" 22 family: af/inet)) 305 ; => #<socket fd:8 af/inet sock/stream> 306 307 ;; Try to connect to localhost:ssh via any address family. 308 ;; In this case, address-information may return the IPv6 loopback 309 ;; address "::1" and perhaps "fe80::1", along with the usual 310 ;; IPv4 "127.0.0.1". socket-connect/ai will try them all in order 311 ;; and return a new connected socket. For illustrative purposes 312 ;; we use socket-peer-name to show where we connected. 313 314 (socket-peer-name 315 (socket-connect/ai (address-information "localhost" "ssh"))) 316 ; => #<sockaddr "[::1]:22"> ;; If ssh listening on ::1 317 ; => #<sockaddr "[fe80::1%lo0]:22"> ;; If listening on link-local loopback 318 ; => #<sockaddr "127.0.0.1:22"> ;; If listening on 127.0.0.1 only 319 ; => error: connection refused ;; If ssh isn't running 320 321<procedure>(socket-bind so saddr)</procedure> 322 323Binds socket SO to socket address SADDR. The return value is unspecified. 324 325 ; Bind to the IPv4 unspecified address on port 8000. 326 (define so (socket af/inet sock/stream)) 327 (socket-bind so (inet-address "0.0.0.0" 8000)) 328 329 ; Bind to the IPv6 unspecified address on port 8000. This may also 330 ; allow IPv4 connections, depending on your system settings. 331 (define so (socket af/inet6 sock/stream)) 332 (socket-bind so (inet-address "::" 8000)) 333 334 ; Bind to the IPv6 unspecified address on port 8000, limiting 335 ; connections to IPv6 only. 336 (define so (socket af/inet6 sock/stream)) 337 (set! (ipv6-v6-only? so) #t) 338 (socket-bind so (inet-address "::" 8000)) 339 340<procedure>(socket-listen so backlog)</procedure> 341 342Listen for incoming connections on socket SO, with a connection queue 343of integer length BACKLOG. This call is only valid for 344connection-oriented (stream) sockets. 345 346<procedure>(socket-accept so)</procedure> 347<procedure>(socket-accept-ready? so)</procedure> 348 349{{socket-accept}} accepts a connection on listening socket SO, 350returning a new connected {{socket}} object. The address of the peer 351can be obtained by calling {{socket-peer-name}} on the socket. 352 353This is a non-blocking operation; other SRFI-18 threads can continue 354to run in the meantime, although this one will block. If the accept 355does not complete within {{(socket-accept-timeout)}} milliseconds, a 356timeout error is raised. 357 358{{socket-accept-ready?}} tests whether there is a connection waiting 359to be accepted, so you can avoid blocking the current thread. 360However, if a peer resets his connection between your testing and 361accepting, the accept may block nonetheless. 362 363<procedure>(socket-shutdown so how)</procedure> 364<constant>shut/rd</constant> 365<constant>shut/wr</constant> 366<constant>shut/rdwr</constant> 367 368Shutdown the full-duplex connection on socket SO in the manner of HOW: 369 370; {{shut/rd}} : disallow further receiving 371; {{shut/wr}} : disallow further sending 372; {{shut/rdwr}} : disallow further receiving and sending 373 374The system normally shuts down the connection itself when closing, 375so calling this manually is not often necessary. One usage example 376is using {{shut/wr}} to inform a server you have finished transmitting, 377while allowing it to continue sending to you. 378 379<procedure>(socket-close so)</procedure> 380 381Close socket SO. If a connection was established, 382the socket is shut down gracefully. 383 384{{socket-close}} throws an error if the {{close()}} fails. 385 386<procedure>(socket-close* so)</procedure> 387 388Same as {{socket-close}}, except that {{socket-close*}} does ''not'' 389throw an error if the {{close()}} fails. 390 391This could be useful in certain lowlevel code, such as after a network 392error, but you should not use this unless you know what you're doing. 393This might go away or change semantics in the future. 394 395=== Status 396 397<procedure>(socket-name so)</procedure> 398 399Return a {{sockaddr}} object representing the address of the local 400endpoint of socket SO. If the socket has not been bound, it 401returns {{#f}}. 402 403The procedure name is derived from getsockname(), hence the use of "name" 404to describe a socket address. 405 406<procedure>(socket-peer-name so)</procedure> 407 408Return a {{sockaddr}} object representing the address of the remote 409endpoint of socket SO. If no connection exists, returns {{#f}}. This 410can be used after {{socket-connect}} or on a socket returned by 411{{socket-accept}}. Note that this also works with UDP "connections" 412made with {{socket-connect}}. 413 414The procedure name is derived from getpeername(), hence the use of "name" 415to describe a socket address. 416 417=== Data transfer 418 419==== Receiving data 420 421<procedure>(socket-receive! so buf #!optional (start 0) (end #f) (flags 0))</procedure> 422<procedure>(socket-receive-ready? so)</procedure> 423 424Receives data from socket SO and writes it into BUF, which may be a 425string or a blob. START and END are optional offsets into BUF; the 426call attempts to read END - START = LEN bytes. If END is {{#f}}, it 427is interpreted as the end of the blob or string. 428 429This call will block until data is available, but other threads can 430proceed. If the receive does not complete within 431{{(socket-receive-timeout)}} milliseconds, a timeout error is raised. 432To avoid blocking the current thread, you can check if data is ready 433via {{socket-receive-ready?}}. 434 435Returns the number of bytes actually received (and updates BUF as 436a side effect). 437 438For datagram sockets, if LEN is smaller than the amount of data in 439the next datagram, the rest of the data is irrevocably lost. 440 441<procedure>(socket-receive so len #!optional (flags 0))</procedure> 442 443Receives up to LEN bytes from data from socket SO and returns it 444in a string (sized to fit the returned data). Otherwise, it behaves 445like {{socket-receive!}}. 446 447<procedure>(socket-receive-from! so buf #!optional (start 0) (end #f) (flags 0))</procedure> 448 449Like {{socket-receive!}}, but receives data on a connectionless 450datagram socket, returning 2 values: the number of bytes read, and a 451{{sockaddr}} object representing the source. 452 453<procedure>(socket-receive-from so len #!optional (flags 0))</procedure> 454 455Receives up to LEN bytes from data from socket SO and returns two 456values: a string (sized to fit the returned data), and a {{sockaddr}} 457object representing the source. Otherwise, it behaves like 458{{socket-receive-from!}}. 459 460==== Sending data 461 462<procedure>(socket-send so buf #!optional (start 0) (end #f) (flags 0))</procedure> 463 464Sends data to socket SO from the buffer BUF, which may be a 465string or a blob. START and END are optional offsets into BUF; the 466call attempts to write END - START = LEN bytes. If END is {{#f}}, it 467is interpreted as the end of the blob or string. 468 469This call will block until at least some data is sent, but other 470threads can proceed. If the send does not complete within 471{{(socket-send-timeout)}} milliseconds, a timeout error is raised. 472 473Returns the number of bytes actually sent. 474 475<procedure>(socket-send-to so buf saddr #!optional (start 0) (end #f) (flags 0))</procedure> 476 477Like {{socket-send}}, but sends data over a connectionless datagram 478socket to {{sockaddr}} SADDR, returning the number of bytes actually 479sent. 480 481<procedure>(socket-send-all so buf #!optional (start 0) (end #f) (flags 0))</procedure> 482 483Sends all data between START and END in BUF over connected socket SO 484by calling {{socket-send}} multiple times until all data is sent. 485 486Data is sent in chunks of size {{(socket-send-size)}}; the last chunk 487sent may be smaller than this. A {{#f}} value for 488{{socket-send-size}} will attempt to send all remaining data with each 489call to send(). Note that this chunking works for connected datagram 490sockets as well as stream sockets; you can use it to send a large 491buffer divided into, say, 512-byte datagrams. 492 493=== I/O ports 494 495<procedure>(socket-i/o-ports so)</procedure> 496 497Constructs an input port I and an output port O associated with 498the connected socket SO, returning {{(values I O)}}. This procedure 499works on both stream and datagram sockets. 500 501To enable output buffering on stream socket ports, see the parameter 502{{socket-send-buffer-size}}. Setting it to a value of 1024 bytes is 503reasonable. 504 505Below is a fairly involved explanation of input and output buffering 506and chunking, as well as recommendations for use with datagrams. 507 508{{socket-i/o-ports}} is normally used with stream sockets. Input data 509is always buffered in a buffer of size {{(socket-receive-buffer-size)}}. 510Whenever the buffer is empty, {{socket-receive!}} is called once to read 511up to that many bytes. Output data is sent with {{socket-send-all}}, 512so it may be divided into chunks of size {{(socket-send-size)}}. If 513output is unbuffered, {{socket-send-all}} is called as soon as data 514is written to the port. 515 516If output is buffered by setting {{(socket-send-buffer-size)}} to N, 517then N characters are buffered before sending the data. Note that 518only multiples of the buffer size are sent (any overage is kept in the 519buffer). For example, if the buffer can hold 512 bytes and contains 520500 bytes, writing 526 more bytes brings the total unsent size to 1026 521bytes. 1024 bytes (2 blocks) are written out in a single call to 522{{socket-send-all}} and the last 2 bytes are retained in the buffer. 523 524When the output buffer size and chunk size are both set, it is 525recommended to make the chunk size a multiple of the buffer size; for 526example, buffer size = 1024, chunk size = 8192. If not aligned, 527extraneous small packets may be sent. Buffer size is almost always 528less than or equal to chunk size. If greater, it should be a multiple 529of the chunk size. Using powers of 2 for both satisfies all cases. 530 531Note that {{socket-i/o-ports}} can also be used to create ports on 532connected datagram sockets. Input is always buffered and a single 533chunk of up to size {{(socket-receive-buffer-size)}} is read into the 534buffer whenever the buffer is empty. (If the datagram is smaller than 535the buffer, repeated reads are not performed; rather, the buffer is 536used until exhausted again. Any datagram exceeding the buffer size 537will be truncated.) Output is divided into chunks of size 538{{(socket-send-size)}}, as in {{socket-send-all}} -- this is useful 539for placing a maximum cap on datagram size transmitted. Finally, 540output buffering may be enabled, which behaves the same as with TCP 541ports; characters are buffered and sent in blocks of 542{{(socket-send-buffer-size)}} bytes. Again, to avoid excessive 543transmission, the chunk size should be a multiple of the buffer 544size or vice versa. 545 546For example, to accept up to 4K datagrams, buffer 128 characters 547at a time and send 128-, 256-, 384- or 512-byte datagrams at a time: 548 549 (parameterize ((socket-receive-buffer-size 4096) 550 (socket-send-buffer-size 128) 551 (socket-send-size 512)) 552 (define so (socket-connect/ai 553 (address-information host port type: sock/dgram))) 554 (define-values (i o) (socket-i/o-ports so)) 555 ;; a useful example would be nice 556 ...) 557 558<procedure>(socket-i/o-port->socket p)</procedure> 559 560Returns the socket object assocated with input or output port P. From 561there you can obtain a file descriptor with {{socket-fileno}}. 562 563Alternatively, {{port->fileno}} from [[/man/4/Unit posix|posix]] is 564supported to obtain a file descriptor. (Also see [[#Bugs and limitations]].) 565 566<procedure>(socket-abandon-port p)</procedure> 567 568Marks the socket input or output port P as abandoned. Normally, when 569an socket input port is closed the read side of the connection is shut 570down; similarly closing the output port shuts down the write side. 571Marking a port as abandoned skips this shutdown. This is useful to 572ensure a connection stays open after the port is closed. 573 574The socket is still closed after both ports are closed, regardless of 575their abandoned status. 576 577=== Parameters 578 579<parameter>(socket-connect-timeout ms) [default: #f]</parameter><br> 580<parameter>(socket-accept-timeout ms) [default: #f]</parameter><br> 581<parameter>(socket-receive-timeout ms) [default: 1 minute]</parameter><br> 582<parameter>(socket-send-timeout ms) [default: 1 minute]</parameter><br> 583 584Timeouts in milliseconds for connect, receive, send and accept 585operations. If these timeout are exceeded, the error {{(exn i/o net timeout)}} 586is raised. If {{#f}}, the operation never times out (unless 587the system forces it to). 588 589<parameter>(socket-send-buffer-size n) [default: #f]</parameter> 590<parameter>(socket-send-size n) [default: 16384]</parameter> 591<parameter>(socket-receive-buffer-size n) [default: 4096]</parameter> 592 593These parameters are used mostly to adjust the behavior of socket ports, 594and take effect when the ports are created. 595 596{{(socket-send-buffer-size)}} is the buffer size used by socket output 597ports. If {{#f}}, no buffering is done. A power of 2, such as 1K or 4K, 598is an appropriate value. 599 600{{(socket-send-size)}} is used by socket output ports, and is the size 601used in a single call to {{socket-send}} by {{socket-send-all}}. It 602can be {{#f}}, meaning infinite, so that any remaining data is sent at 603each call. When set, it should usually be a multiple of 604{{(socket-send-buffer-size)}}, assuming buffering is also enabled. A 605power of 2 is an appropriate value, such as 8K or 16K. 606 607{{(socket-receive-buffer-size)}} is the size used for the input buffer 608in socket input ports. A power of 2, such as 4K, is appropriate. 609Input buffering can not be disabled. 610 611== Socket option interface 612 613BSD socket option values are of substantially differing types: boolean flags 614(TCP_NODELAY), integers (SO_SNDBUF), structures (SO_LINGER), and so on. Still, we want a 615consistent interface and an element of type-safety as well. So for each option, we 616provide a unique getter / setter procedure which does the type-checking and marshals 617(or unmarshals) the data as needed. 618 619Each getter / setter takes a socket argument. The "socket" is either 620a file descriptor number, as returned by a socket() call, or a socket object 621as provided in this extension. SRFI-17 generalized set! is used on the 622getters to set socket options. 623 624 (tcp-no-delay? s) ; => #t or #f 625 (set! (tcp-no-delay s) #t) 626 627An error is thrown if the socket call fails, if the value passed is of 628incorrect type, or if you try to set a read-only option. 629 630An error of {{(exn i/o net unsupported)}} is thrown if you try to use 631a socket option that is not defined at all on the platform, or that is 632defined but not supported by the operating system. Note that some 633platforms, particularly Windows, may return a false positive for 634"unsupported option" when it really indicates a usage error (wrong 635socket type or option value). 636 637=== Socket option accessors 638 639Below is a list of option procedures and their value type. The procedure names are 640verbose variants of their associated constant names. For example, {{SO_REUSEADDR}} becomes 641{{so-reuse-address}}. 642 643Only booleans and integers and their read-only variants are currently supported. The 644intention is to additionally support timevals, linger, ip_mreq structs and ipoptions, at 645least. There is an example of linger support in the low-level interface below. 646 647<procedure>(so-reuse-address? s) [so/reuseaddr] </procedure><br> 648<procedure>(so-debug? s) [so/debug] </procedure><br> 649<procedure>(so-keep-alive? s) [so/keepalive] </procedure><br> 650<procedure>(so-dont-route? s) [so/dontroute] </procedure><br> 651<procedure>(so-broadcast? s) [so/broadcast] </procedure><br> 652<procedure>(so-oob-inline? s) [so/oobinline] </procedure><br> 653<procedure>(so-accept-connections? s) [so/acceptconn] (r/o)</procedure><br> 654<procedure>(so-send-buffer s) [so/sndbuf] </procedure><br> 655<procedure>(so-receive-buffer s) [so/rcvbuf] </procedure><br> 656<procedure>(so-send-low-water s) [so/sndlowat] </procedure><br> 657<procedure>(so-receive-low-water s) [so/rcvlowat] </procedure><br> 658<procedure>(so-error s) [so/error] (r/o)</procedure><br> 659<procedure>(so-type s) [so/type] (r/o)</procedure><br> 660 661Getters / setters for boolean and integer socket-level options, where S is a 662''socket'' object or an integer file descriptor. To set an option, use SRFI-17 663generalized set: 664 665 (set! (so-reuse-address? s) #t) 666 667"(r/o)" indicates the option is read-only; an error will be raised if 668you attempt to set it. 669 670As a special note on {{so-reuse-address?}}, on Windows platforms it 671will first attempt to use option {{so/exclusiveaddruse}} because this 672option matches UNIX semantics. If this fails it will fall back to 673{{so/reuseaddr}}, which allows any processes to rebind a previously 674bound address and port. 675 676<procedure>(tcp-no-delay? s) [tcp/nodelay]</procedure><br> 677<procedure>(tcp-no-push? s) [tcp/nopush]</procedure><br> 678<procedure>(tcp-no-options? s) [tcp/noopt]</procedure><br> 679<procedure>(tcp-keep-alive s) [tcp/keepalive]</procedure><br> 680<procedure>(tcp-max-segment-size s) [tcp/maxseg]</procedure><br> 681 682Getters / setters for TCP-level socket options ({{ipproto/tcp}}). S is 683a ''socket'' object or an integer file descriptor. 684 685<procedure>(ip-header-included? s) [ip/hdrincl]</procedure><br> 686<procedure>(ip-type-of-service s) [ip/tos]</procedure><br> 687<procedure>(ip-time-to-live s) [ip/ttl]</procedure><br> 688 689Getters / setters for IP-level socket options ({{ipproto/ip}}). S is 690a ''socket'' object or an integer file descriptor. 691 692<procedure>(ipv6-v6-only? s) [ipv6/v6only] </procedure><br> 693 694Getters / setters for IPv6-level socket options ({{ipproto/ipv6}}). S is 695a ''socket'' object or an integer file descriptor. 696 697=== Low-level socket option interface 698 699A low-level socket option interface is also provided. This is 700intended to let you use the constants defined above (or your own) when 701there is no high-level interface implemented. This interface can get 702or set arbitrary option contents; you're not limited to predefined 703types such as integer or boolean. No checking is done that the passed 704option value is appropriate, as that's the job of the high-level 705interface. 706 707<procedure>(set-socket-option s level name val)</procedure> 708 709Set the value of option {{NAME}} at socket level {{LEVEL}} on socket {{S}} to {{VAL}}. 710{{VAL}} may be a fixnum or a boolean. It may also be a blob or a string; if so, the raw 711contents are passed to the option, which is useful when a structure is required. The return value is unspecified. 712 713If an unsupported option or level is requested, a condition of type 714{{(exn i/o net unsupported)}} is raised. 715 716Note: due to the vagaries of structure member alignment (and 32 vs. 64-bit sizes), it's 717not generally safe to pack raw data yourself into a blob or a SRFI-4 vector. Instead, you 718should treat the blob contents as a C struct. See the longer example down the page 719for more. 720 721 (set-socket-option S ipproto/tcp tcp/nodelay 1) 722 (set-socket-option S ipproto/tcp tcp/nodelay (make-string 4 #\x0)) 723 (set-socket-option S sol/socket so/rcvlowat (u32vector->blob/shared (u32vector #x01020304))) 724 725<procedure>(get-socket-option s level name #!optional (len #f))</procedure> 726 727Get the value of option {{NAME}} at socket level {{LEVEL}} on socket 728{{S}}. If {{LEN}} is {{#f}}, the default, we interpret the option 729value as an integer and return that. Otherwise, temporary storage of 730length {{LEN}} is allocated to receive the binary option data; after 731the call it is resized to fit the data, and returned. If LEN is too 732small to hold the returned data, the result is undefined. 733 734If an unsupported option or level is requested, a condition of type 735{{(exn i/o net unsupported)}} is raised. 736 737This procedure does not convert integers to boolean values---if you 738expect a boolean flag, assume zero means {{#f}} and non-zero means 739{{#t}}. Don't be surprised if boolean flags return different non-zero 740integer values from those you put in; that's an implementation detail. 741You can only rely on true being some non-zero value. 742 743 (get-socket-option S ipproto/tcp tcp/nodelay) ; => 8, perhaps, meaning #t 744 (get-socket-option S ipproto/tcp tcp/nodelay 64) ; => #${08000000} 745 (get-socket-option S ipproto/tcp tcp/nodelay 4) ; => #${08000000} 746 747=== Socket option constants 748 749Integer constants are provided for socket levels, socket types, and 750socket options. They are renamed slightly, and consistently, to 751achieve a more Schemely appearance: for example, C's {{SO_REUSEADDR}} 752becomes {{so/reuseaddr}}. 753 754Some platforms do not define all the constants we provide. If a 755constant is undefined, its value is {{#f}} and attempting to get or 756set it will raise an error. Note that a platform may define a 757constant but not support it (for example, {{ipv6/v6only}} on Windows 758prior to Vista); this will not be known until you try to get or set 759it. 760 761==== Socket-level constants 762 763<constant>so/reuseaddr</constant><br> 764<constant>so/debug</constant><br> 765<constant>so/acceptconn</constant><br> 766<constant>so/keepalive</constant><br> 767<constant>so/dontroute</constant><br> 768<constant>so/broadcast</constant><br> 769<constant>so/linger</constant><br> 770<constant>so/oobinline</constant><br> 771<constant>so/sndbuf</constant><br> 772<constant>so/rcvbuf</constant><br> 773<constant>so/sndlowat</constant><br> 774<constant>so/rcvlowat</constant><br> 775<constant>so/sndtimeo</constant><br> 776<constant>so/rcvtimeo</constant><br> 777<constant>so/error</constant><br> 778<constant>so/type</constant><br> 779<constant>so/useloopback</constant><br> 780<constant>so/reuseport</constant><br> 781<constant>so/timestamp</constant><br> 782<constant>so/exclusiveaddruse</constant><br> 783 784Socket-level socket options for use with {{set-socket-option}} and 785{{get-socket-option}} at level {{sol/socket}}. 786 787==== TCP-level constants 788 789<constant>tcp/nodelay</constant><br> 790<constant>tcp/nopush</constant><br> 791<constant>tcp/noopt</constant><br> 792<constant>tcp/keepalive</constant><br> 793<constant>tcp/maxseg</constant><br> 794 795TCP-level socket options for use with {{set-socket-option}} and 796{{get-socket-option}} at level {{ipproto/tcp}}. 797 798==== IP-level constants 799 800<constant>ip/options</constant><br> 801<constant>ip/hdrincl</constant><br> 802<constant>ip/tos</constant><br> 803<constant>ip/ttl</constant><br> 804<constant>ip/mtu</constant><br> 805<constant>ip/mtu-discover</constant><br> 806<constant>ip/pktinfo</constant><br> 807<constant>ip/recverr</constant><br> 808<constant>ip/recvtos</constant><br> 809<constant>ip/recvttl</constant><br> 810<constant>ip/router-alert</constant><br> 811<constant>ip/recvopts</constant><br> 812<constant>ip/recvretopts</constant><br> 813<constant>ip/retopts</constant><br> 814<constant>ip/recvdstaddr</constant><br> 815<constant>ip/multicast-if</constant><br> 816<constant>ip/multicast-ttl</constant><br> 817<constant>ip/multicast-loop</constant><br> 818<constant>ip/add-membership</constant><br> 819<constant>ip/drop-membership</constant><br> 820 821IP-level socket options for use with {{set-socket-option}} and 822{{get-socket-option}} at level {{ipproto/ip}}. 823 824==== Socket and protocol levels 825 826<constant>sol/socket</constant><br> 827<constant>ipproto/ip</constant><br> 828<constant>ipproto/ipv6</constant><br> 829<constant>ipproto/tcp</constant><br> 830<constant>ipproto/icmp</constant><br> 831<constant>ipproto/udp</constant><br> 832 833Socket level constants, for use with {{set-socket-option}} and {{get-socket-option}}. 834 835=== SO_LINGER lowlevel example 836 837This is a pretty hairy example of getting and setting the {{so/linger}} option, which does 838not currently have a high-level equivalent. {{so/linger}} usually takes and returns a 839{{struct linger}} value which consists of an on/off flag and a linger timeout in seconds. 840(But not always!) 841 842The approach below encases the {{struct linger}} in an 843appropriately-sized blob and creates an encoder and decoder for this 844structure. Any useful option taking a structure value should ideally 845have a high-level interface created for it instead. 846 847 (define _linger_size (foreign-value "sizeof(struct linger)" int)) 848 (define (encode-linger-option state time) 849 (let ((blob (make-blob _linger_size))) 850 ((foreign-lambda* void ((scheme-pointer ptr) (bool onoff) (int linger)) 851 "struct linger *p = ptr;" 852 "p->l_onoff = onoff; p->l_linger = linger;") 853 blob state time) 854 blob)) 855 (define (decode-linger-option blob) 856 ; sanity checking on parameter recommended here 857 (list ((foreign-lambda* bool ((scheme-pointer p)) 858 "return(((struct linger *)p)->l_onoff);") blob) 859 ((foreign-lambda* int ((scheme-pointer p)) 860 "return(((struct linger *)p)->l_linger);") blob))) 861 862 (set-socket-option S sol/socket so/linger (encode-linger-option #t 100)) 863 (decode-linger-option 864 (get-socket-option S sol/socket so/linger _linger_size)) 865 ; => (#t 100) 866 867== Examples 868 869=== Client-server examples 870 871For a simple example of client-server communication over a unix socket, see 872[[/Communicating over a unix socket, using the socket egg|here]]. 873 874A TCP/IP example is still to be written. 875 876=== Disable Nagle's Algorithm on TCP listener socket 877 878The [[/man/4/Unit tcp|tcp unit]] does not support setting arbitrary socket 879options on sockets it creates. However, you can obtain a listener's 880socket file descriptor after the fact. 881 882 (define L (tcp-listen 8080)) 883 (define S (tcp-listener-fileno L)) 884 (set! (tcp-no-delay? S) #t) 885 886=== Set socket options on HTTP server 887 888This is similar to the above. HTTP servers may see some performance 889gain when Nagle's algorithm is disabled. This is generally the 890default on Linux, but not Solaris or OS X. 891 892(This needs to be updated for spiffy / intarweb.) 893 894 (parameterize ((http:listen-procedure 895 (lambda (port backlog host) 896 (let ((L (tcp-listen port backlog host))) 897 (set! (tcp-no-delay? (tcp-listener-fileno L) #t)) 898 L)))) 899 ((http:make-server ...))) 900 901== Bugs and limitations 902 903* If IPv6 support is totally unavailable on your platform (not simply disabled) 904 then building this extension will fail. This should be fixed in a future 905 release. 906 907* In order to support {{port->fileno}}, socket ports are 908 backwardly-compatible with core tcp ports to the extent that 909 port-related procedures from [[/man/4/Unit tcp|Unit tcp]] will 910 erroneously accept socket ports as well. These procedures are 911 {{tcp-abandon-port}}, {{tcp-addresses}}, and {{tcp-port-numbers}}. 912 Using them with socket ports has an undefined result. The other way 913 around is safe: procedures in this extension will throw an error if 914 used with core tcp ports. 915 916== About this egg 917 918=== Author 919 920[[http://3e8.org|Jim Ursetto]] 921 922Some code was derived from the core [[/man/4/Unit tcp|tcp]] 923unit by Felix Winkelmann and the rest of the Chicken team. 924 925=== Version history 926 927; 0.2.5 : socket-accept: Handle select failure. Patch by Jonathan Chan. 928; 0.2.4 : {{SO_EXCLUSIVEADDR}} fix for Cygwin 929; 0.2.3 : Set connectionless sockets to nonblocking 930; 0.2.2 : Fix segfault in {{socket-receive}}, {{socket-send}} and friends when socket argument was not a socket (reported by hypnocat) 931; 0.2.1 : Treat string {{addr}} arg to {{name-information}} as {{(inet-address addr #f)}} 932; 0.2 : Add UNIX socket support; eliminate much dead code and runtime support checks. 933; 0.1 : Initial release for Chicken 4. 934 935=== Portability 936 937* socket 0.1 has been successfully built and tested on Mac OS X 10.5, 938 Ubuntu 10.10, Windows XP SP3 and NetBSD 5.1. 939 940=== License 941 942 Copyright (c) 2011-2014, Jim Ursetto. All rights reserved. 943 Copyright (c) 2008-2011, The Chicken Team 944 Copyright (c) 2000-2007, Felix L. Winkelmann 945 946 Redistribution and use in source and binary forms, with or without 947 modification, are permitted provided that the following conditions are met: 948 949 Redistributions of source code must retain the above copyright notice, 950 this list of conditions and the following disclaimer. Redistributions in 951 binary form must reproduce the above copyright notice, this list of 952 conditions and the following disclaimer in the documentation and/or 953 other materials provided with the distribution. Neither the name of the 954 author nor the names of its contributors may be used to endorse or 955 promote products derived from this software without specific prior 956 written permission. 957 958 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 959 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 960 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 961 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR 962 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 963 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 964 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 965 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 966 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 967 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 968 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 969