Reputation: 2095
While iterating through socket file descriptors, how can I check if one of them is from a passive socket (listening for connections)?
Upvotes: 16
Views: 8046
Reputation: 60843
This can be checked with getsockopt(SO_ACCEPTCONN). For example:
#include <sys/socket.h>
int val;
socklen_t len = sizeof(val);
if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &val, &len) == -1)
printf("fd %d is not a socket\n", fd);
else if (val)
printf("fd %d is a listening socket\n", fd);
else
printf("fd %d is a non-listening socket\n", fd);
Upvotes: 26
Reputation:
Strictly speaking, you could try performing an operation on the socket which would incidentally determine what type of socket it is, like trying to accept a connection from it. If accept()
fails with EINVAL, that's a pretty good sign that it isn't listening. :)
Keeping track of which sockets are which is a better solution overall, though. Unless you're building a really trivial application, chances are that you'll need to keep some sort of additional data on each socket anyway.
Upvotes: 0
Reputation: 11
You can run in the command line (on a Mac/Linux enviroment):
lsof -i
and/or (Linux/Mac/Windows enviroment)
netstat -a
Upvotes: 0