The socket APIs provide many functions for use in network programming. Here are the common socket functions that we use in this book:
- socket() creates and initializes a new socket.
- bind() associates a socket with a particular local IP address and port number.
- listen() is used on the server to cause a TCP socket to listen for new connections.
- connect() is used on the client to set the remote address and port. In the case of TCP, it also establishes a connection.
- accept() is used on the server to create a new socket for an incoming TCP connection.
- send() and recv() are used to send and receive data with a socket.
- sendto() and recvfrom() are used to send and receive data from sockets without a bound remote address.
- close() (Berkeley sockets) and closesocket() (Winsock sockets) are used to close a socket. In the case of TCP, this also terminates the connection.
- shutdown() is used to close one side of a TCP connection. It is useful to ensure an orderly connection teardown.
- select() is used to wait for an event on one or more sockets.
- getnameinfo() and getaddrinfo() provide a protocol-independent manner of working with hostnames and addresses.
- setsockopt() is used to change some socket options.
- fcntl() (Berkeley sockets) and ioctlsocket() (Winsock sockets) are also used to get and set some socket options.
You may see some Berkeley socket networking programs using read() and write(). These functions don't port to Winsock, so we prefer send() and recv() here. Some other common functions that are used with Berkeley sockets areĀ poll() and dup(). We will avoid these in order to keep our programs portable.
Other differences between Berkeley sockets and Winsock sockets are addressed later in this chapter.
Now that we have an idea of the functions involved, let's consider program design and flow next.