I am trying to determine whether a TCP port that was bound by a process, that was recently started, is actually in use by that particular process.
Take this program.cpp
int daemonport = 11234;
struct sockaddr_in loopback;
memset ((char*) &loopback, 0, sizeof (loopback));
socklen_t len = sizeof (loopback);
loopback.sin_family = AF_INET;
loopback.sin_port = htons (daemonport);
loopback.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
daemonfd = socket (AF_INET, SOCK_STREAM, 0);
if (daemonfd < 0)
{
errx (EXIT_FAILURE, "Critical error");
}
if (bind (daemonfd, (struct sockaddr*) &loopback, sizeof (loopback)) != 0)
{
errx (EXIT_FAILURE, "Daemon already running, TCP port: '%d'", daemonport);
}
if (getsockname (daemonfd, (struct sockaddr*) &loopback, &len) != 0)
{
errx (EXIT_FAILURE, "Critical error");
}
printf ("%d\n", ntohs (loopback.sin_port));
if (daemon (1, 0) < 0)
{
close (daemonfd);
errx (EXIT_FAILURE, "Failed to daemonize!");
}
// event loop...
close (daemonfd);
Now with the tcp socket bound (but not listening) to port 11234 I want to check whether the port is bound by the process using a bash script.
I tried various netstat and lsof patterns w/o success:
netstat -a | grep ':11234'
as well as lsof -i :11234
.
They all don't print a line with the bound port.
But when I try to run the program a 2nd time it errors out with:
Daemon already running, TCP port: '11234'