本文摘自:C++ Network Programming, Volume 1: Mastering Complexity with ACE and Patterns
Socket API共有20多个函数,被分为5大类。
1、Local context management. The Socket API provides functions to manage local context information, which is normally stored within the OS kernel or in system libraries:
Function | Description |
---|---|
Socket() | A factory function that allocates a socket handle and returns it to the caller. |
bind() | Associates a socket handle with a local or remote address. |
getsockname() | Returns the local address to which a socket is bound. |
getpeername() | Returns the remote address to which a socket is bound. |
close() | Deallocates a socket handle, making it available for reuse. |
-
2、Connection establishment and connection termination. The Socket API provides functions to establish and terminate connections:
Function Description Connect() Establishes a connection actively on a socket handle. listen() Indicates its willingness to listen passively for incoming client connection requests. Accept() A factory function that creates a new communication endpoint to service client requests. shutdown() Selectively terminates the read-side and/or write-side stream of a bidirectional connection. -
3、Data transfer mechanisms. The Socket API provides functions to send and receive data via socket handles:
Function Description send()recv()
Transmit and receive buffers of data via a particular I/O handle. sendto()recvfrom()
Exchanges connectionless datagrams, where each sendto() call provides the networking address of the recipient. On UNIX, these functions can also be used for other types of 1/O handles, such as files and terminal devices. UNIX platforms also provide the following data transfer mechanisms:
Function Description read()write()
Receive and transmit buffers of data via a particular handle. readv()writev()
Supports scatter-read and gather-write semantics, respectively, to optimize mode switching and simplify memory management. sendmsg()recvmsg()
General-purpose functions that subsume the behavior of the other data transfer functions. -
4、Options management. The Socket API defines functions that allow programmers to alter default socket behavior to enable multicasting, broadcasting, and modifying/querying the size of transport buffers:
Function Description setsockopt() Modifies options in different protocol stack layers. getsockopt() Queries options in different protocol stack layers. -
5、Network addressing. In addition to the functions described above, networked applications often use functions to resolve humanly readable names, such as tango.ece.uci.edu, to low-level network addresses, such as 128.195.174.35:
Function Description gethostbyname() gethostbyaddr()
Handle network address mapping between hostnames and IPv4 addresses. getipnodebyname() getipnodebyaddr()
Handle network address mapping between hostnames and IPv4/IPv6 addresses. get servbyname() Identifies services by their humanly readable names.