accept |
Prototype: |
#include <sys/socket.h>
#include <resolv.h>
int accept(int sockfd, struct sockaddr *addr, int *addr_len);
|
General Description: |
Wait for a connection. When a connection arrives, return a new socket descriptor (independent to sockfd) for that specific connection. This call is only available to SOCK_STREAM sockets. |
Return Value: |
If >= 0, a new socket descriptor. If < 0, error; errno has details. |
Parameters |
sockfd |
The bound and listening socket descriptor. |
addr |
If nonzero, the call places the address definition in this region. While it should match the sockfd's family (AF_INET), do not assume it. |
addr_len |
You pass the length by reference so that the call can tell you exactly how much of addr's data block it used. This means that you need to reset the value for each call. |
Possible Errors |
EBADF |
The socket descriptor is invalid. |
ENOTSOCK |
The descriptor references a file, not a socket. |
EOPNOTSUPP |
The referenced socket is not of type SOCK_STREAM. |
EFAULT |
The addr parameter is not in a writable part of the user address space. |
EAGAIN |
The socket is marked non-blocking and no connections are present to be accepted. |
EPERM |
Firewall rules forbid connection.ENOBUFS, ENOMEMNot enough free memory. |
Examples |
int sockfd = socket(PF_INET, SOCK_STREAM, 0);
/*---bind address to socket with bind()---*/
/*---convert it to a listening socket with listen()---*/
for (;;)
{ int client;
client = accept(sockfd, 0, 0);
/*---interact with client---*/
close(client);
}
|
int sockfd = socket(PF_INET, SOCK_STREAM, 0);
/*---bind address to socket with bind()---*/
/*---convert it to a listening socket with listen()---*/
for (;;)
{ struct sockaddr_in addr;
int client, addr_len = addr;
client = accept(sockfd, &addr, &addr_len);
printf("Connected: %s:%d\n", inet_ntoa(addr.sin_addr),
ntohs(addr.sin_port));
/*---interact with client---*/
close(client);
}
|