📄 socket.texi
字号:
The system already has too many file descriptors open.@item EACCESSThe process does not have privilege to create a socket of the specified@var{style} or @var{protocol}.@item ENOBUFSThe system ran out of internal buffer space.@end tableThe file descriptor returned by the @code{socket} function supports bothread and write operations. But, like pipes, sockets do not support filepositioning operations.@end deftypefunFor examples of how to call the @code{socket} function, see @ref{File Namespace}, or @ref{Inet Example}.@node Closing a Socket@subsection Closing a Socket@cindex socket, closing@cindex closing a socket@cindex shutting down a socket@cindex socket shutdownWhen you are finished using a socket, you can simply close itsfile descriptor with @code{close}; see @ref{Opening and Closing Files}.If there is still data waiting to be transmitted over the connection,normally @code{close} tries to complete this transmission. Youcan control this behavior using the @code{SO_LINGER} socket option tospecify a timeout period; see @ref{Socket Options}.@pindex sys/socket.hYou can also shut down only reception or only transmission on aconnection by calling @code{shutdown}, which is declared in@file{sys/socket.h}.@comment sys/socket.h@comment BSD@deftypefun int shutdown (int @var{socket}, int @var{how})The @code{shutdown} function shuts down the connection of socket@var{socket}. The argument @var{how} specifies what action toperform:@table @code@item 0Stop receiving data for this socket. If further data arrives,reject it.@item 1Stop trying to transmit data from this socket. Discard any datawaiting to be sent. Stop looking for acknowledgement of data alreadysent; don't retransmit it if it is lost.@item 2Stop both reception and transmission.@end tableThe return value is @code{0} on success and @code{-1} on failure. Thefollowing @code{errno} error conditions are defined for this function:@table @code@item EBADF@var{socket} is not a valid file descriptor.@item ENOTSOCK@var{socket} is not a socket.@item ENOTCONN@var{socket} is not connected.@end table@end deftypefun@node Socket Pairs@subsection Socket Pairs@cindex creating a socket pair@cindex socket pair@cindex opening a socket pair@pindex sys/socket.hA @dfn{socket pair} consists of a pair of connected (but unnamed)sockets. It is very similar to a pipe and is used in much the sameway. Socket pairs are created with the @code{socketpair} function,declared in @file{sys/socket.h}. A socket pair is much like a pipe; themain difference is that the socket pair is bidirectional, whereas thepipe has one input-only end and one output-only end (@pxref{Pipes andFIFOs}).@comment sys/socket.h@comment BSD@deftypefun int socketpair (int @var{namespace}, int @var{style}, int @var{protocol}, int @var{filedes}@t{[2]})This function creates a socket pair, returning the file descriptors in@code{@var{filedes}[0]} and @code{@var{filedes}[1]}. The socket pairis a full-duplex communications channel, so that both reading and writingmay be performed at either end.The @var{namespace}, @var{style}, and @var{protocol} arguments areinterpreted as for the @code{socket} function. @var{style} should beone of the communication styles listed in @ref{Communication Styles}.The @var{namespace} argument specifies the namespace, which must be@code{AF_FILE} (@pxref{File Namespace}); @var{protocol} specifies thecommunications protocol, but zero is the only meaningful value.If @var{style} specifies a connectionless communication style, thenthe two sockets you get are not @emph{connected}, strictly speaking,but each of them knows the other as the default destination address,so they can send packets to each other.The @code{socketpair} function returns @code{0} on success and @code{-1}on failure. The following @code{errno} error conditions are definedfor this function:@table @code@item EMFILEThe process has too many file descriptors open.@item EAFNOSUPPORTThe specified namespace is not supported.@item EPROTONOSUPPORTThe specified protocol is not supported.@item EOPNOTSUPPThe specified protocol does not support the creation of socket pairs.@end table@end deftypefun@node Connections@section Using Sockets with Connections@cindex connection@cindex client@cindex serverThe most common communication styles involve making a connection to aparticular other socket, and then exchanging data with that socketover and over. Making a connection is asymmetric; one side (the@dfn{client}) acts to request a connection, while the other side (the@dfn{server}) makes a socket and waits for the connection request.@iftex@itemize @bullet@item@ref{Connecting}, describes what the client program must do toinitiate a connection with a server.@item@ref{Listening}, and @ref{Accepting Connections}, describe what theserver program must do to wait for and act upon connection requestsfrom clients.@item@ref{Transferring Data}, describes how data is transferred through theconnected socket.@end itemize@end iftex@menu* Connecting:: What the client program must do.* Listening:: How a server program waits for requests.* Accepting Connections:: What the server does when it gets a request.* Who is Connected:: Getting the address of the other side of a connection.* Transferring Data:: How to send and receive data.* Byte Stream Example:: An example program: a client for communicating over a byte stream socket in the Internet namespace.* Server Example:: A corresponding server program.* Out-of-Band Data:: This is an advanced feature.@end menu@node Connecting@subsection Making a Connection@cindex connecting a socket@cindex socket, connecting@cindex socket, initiating a connection@cindex socket, client actionsIn making a connection, the client makes a connection while the serverwaits for and accepts the connection. Here we discuss what the clientprogram must do, using the @code{connect} function, which is declared in@file{sys/socket.h}.@comment sys/socket.h@comment BSD@deftypefun int connect (int @var{socket}, struct sockaddr *@var{addr}, size_t @var{length})The @code{connect} function initiates a connection from the socketwith file descriptor @var{socket} to the socket whose address isspecified by the @var{addr} and @var{length} arguments. (This socketis typically on another machine, and it must be already set up as aserver.) @xref{Socket Addresses}, for information about how thesearguments are interpreted.Normally, @code{connect} waits until the server responds to the requestbefore it returns. You can set nonblocking mode on the socket@var{socket} to make @code{connect} return immediately without waitingfor the response. @xref{File Status Flags}, for information aboutnonblocking mode.@c !!! how do you tell when it has finished connecting? I suspect the@c way you do it is select for writing.The normal return value from @code{connect} is @code{0}. If an erroroccurs, @code{connect} returns @code{-1}. The following @code{errno}error conditions are defined for this function:@table @code@item EBADFThe socket @var{socket} is not a valid file descriptor.@item ENOTSOCKThe socket @var{socket} is not a socket.@item EADDRNOTAVAILThe specified address is not available on the remote machine.@item EAFNOSUPPORTThe namespace of the @var{addr} is not supported by this socket.@item EISCONNThe socket @var{socket} is already connected.@item ETIMEDOUTThe attempt to establish the connection timed out.@item ECONNREFUSEDThe server has actively refused to establish the connection.@item ENETUNREACHThe network of the given @var{addr} isn't reachable from this host.@item EADDRINUSEThe socket address of the given @var{addr} is already in use.@item EINPROGRESSThe socket @var{socket} is non-blocking and the connection could not beestablished immediately.@item EALREADYThe socket @var{socket} is non-blocking and already has a pendingconnection in progress.@end table@end deftypefun@node Listening@subsection Listening for Connections@cindex listening (sockets)@cindex sockets, server actions@cindex sockets, listeningNow let us consider what the server process must do to acceptconnections on a socket. First it must use the @code{listen} functionto enable connection requests on the socket, and then accept eachincoming connection with a call to @code{accept} (@pxref{AcceptingConnections}). Once connection requests are enabled on a server socket,the @code{select} function reports when the socket has a connectionready to be accepted (@pxref{Waiting for I/O}).The @code{listen} function is not allowed for sockets usingconnectionless communication styles.You can write a network server that does not even start running until aconnection to it is requested. @xref{Inetd Servers}.In the Internet namespace, there are no special protection mechanismsfor controlling access to connect to a port; any process on any machinecan make a connection to your server. If you want to restrict access toyour server, make it examine the addresses associated with connectionrequests or implement some other handshaking or identificationprotocol.In the File namespace, the ordinary file protection bits control who hasaccess to connect to the socket.@comment sys/socket.h@comment BSD@deftypefun int listen (int @var{socket}, unsigned int @var{n})The @code{listen} function enables the socket @var{socket} to acceptconnections, thus making it a server socket.The argument @var{n} specifies the length of the queue for pendingconnections. When the queue fills, new clients attempting to connectfail with @code{ECONNREFUSED} until the server calls @code{accept} toaccept a connection from the queue.The @code{listen} function returns @code{0} on success and @code{-1}on failure. The following @code{errno} error conditions are definedfor this function:@table @code@item EBADFThe argument @var{socket} is not a valid file descriptor.@item ENOTSOCKThe argument @var{socket} is not a socket.@item EOPNOTSUPPThe socket @var{socket} does not support this operation.@end table@end deftypefun@node Accepting Connections@subsection Accepting Connections@cindex sockets, accepting connections@cindex accepting connectionsWhen a server receives a connection request, it can complete theconnection by accepting the request. Use the function @code{accept}to do this.A socket that has been established as a server can accept connectionrequests from multiple clients. The server's original socket@emph{does not become part} of the connection; instead, @code{accept}makes a new socket which participates in the connection.@code{accept} returns the descriptor for this socket. The server'soriginal socket remains available for listening for further connectionrequests.The number of pending connection requests on a server socket is finite.If connection requests arrive from clients faster than the server canact upon them, the queue can fill up and additional requests are refusedwith a @code{ECONNREFUSED} error. You can specify the maximum length ofthis queue as an argument to the @code{listen} function, although thesystem may also impose its own internal limit on the length of thisqueue.@comment sys/socket.h@comment BSD@deftypefun int accept (int @var{socket}, struct sockaddr *@var{addr}, size_t *@var{length-ptr})This function is used to accept a connection request on the serversocket @var{socket}.The @code{accept} function waits if there are no connections pending,unless the socket @var{socket} has nonblocking mode set. (You can use@code{select} to wait for a pending connection, with a nonblockingsocket.) @xref{File Status Flags}, for information about nonblockingmode.The @var{addr} and @var{length-ptr} arguments are used to returninformation about the name of the client socket that initiated theconnection. @xref{Socket Addresses}, for information about the formatof the information.Accepting a connection does not make @var{socket} part of theconnection. Instead, it creates a new socket which becomesconnected. The normal return value of @code{accept} is the filedescriptor for the new socket.After @code{accept}, the original socket @var{socket} remains open andunconnected, and continues listening until you close it
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -