Mihai Neacsu
Mihai Neacsu

Reputation: 2095

Check if socket is listening in C

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

Answers (3)

mark4o
mark4o

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

user149341
user149341

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

ringneckparrot
ringneckparrot

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

Related Questions