TCP/IP Programming Manual

Errors
If an error occurs, the external variable errno is set to one of the following values:
The connection was reset by the peer process before the accept operation completed.ECONNRESET
An invalid argument was specified.EINVAL
Usage Guidelines
This is a waited call; your program is blocked until the operation completes. For nowait I/O,
use accept_nw and accept_nw2.
For TCP server applications, a call to bind and listen must precede a call to accept.
The original socket remains in a listening state.
Declare the from_ptr variable as struct sockaddr_in6 * for IPv6 use or as struct
sockaddr_storage * for protocol-independent use. In C, when you make the call, cast
the variable to sockaddr. (See the IPv6 example.)
Examples
The following programming example calls the accept function to accept a connection on a TCP
socket.
INET: in this example, assume that fd is the socket number returned by a call to socket.
#include <socket.h>
#include <in.h>
#include <netdb.h>
...
struct sockaddr_in sin, from;
int flen;
char buf[256];
/* Before accept, program must call socket, bind,
* and listen.
*/
flen = sizeof(from);
if ((s2 = accept(fd, (struct sockaddr *)&from, &flen)) < 0) {
perror ("Server: Accept failed.");
exit (0);
}
inet_ntop (AF_INET, &from->sin_addr, buf, INET_ADDRSTRLEN);
printf ("Server connected from remote %s, %d\n", buf, from.sin_port);
INET6: In this example, assume fd is the socket number returned by a call to socket.
#include <socket.h>
#include <in.h>
#include <in6.h>
#include <netdb.h>
...
struct sockaddr_in6, from;
int flen;
char buf[INET6_ADDRSTRLEN];
/* Before accept, program must call socket, bind,
* and listen.
*/
flen = sizeof(from);
90 Library Routines