[comp.unix.questions] is it a socket or is it not?

generous@dgis.daitc.mil (Curtis Generous) (07/30/89)

What's a good method of determining whether a file descriptor
is a socket or not?  The fstat(2) call does not work well on sockets
(and it even says so in the man page :-)

This is what I would like to do but doesn't work:

    if (fstat(fildes, &statb) == 0) {
	if ((statb.st_mode &= S_IFMT) == S_IFSOCK)
	    sockflag++;
    }

Is there a better/cleaner way?  Do you go through the list of possibles
and work by elimination (S_IFREG, S_IFDIR, ...)?  Can I assume that fstat(2)
will _always_ return a zeroed buffer as mentioned in the BUGS of the man page?

The OS is More/BSD 4.3 on a VAX 780, but I think this spans many BSD derivatives

--curtis
-- 
Curtis C. Generous
DTIC Special Projects Office (DTIC-SPO)
ARPA: generous@daitc.mil
UUCP: {uunet,vrdxhq,lll-tis}!daitc!generous

madd@bu-cs.BU.EDU (Jim Frost) (08/12/89)

In article <8@dgis.daitc.mil> generous@dgis.daitc.mil (Curtis Generous) writes:
|What's a good method of determining whether a file descriptor
|is a socket or not?  The fstat(2) call does not work well on sockets
|(and it even says so in the man page :-)

Probably the easiest way is:

int isASocket(s)
	int s;
{ struct sockaddr name;
  int             len;

  if ((getsockname(s, &name, &len) < 0) && (errno == ENOTSOCK))
    return(0);
  else
    return(1);
}

You could probably use a variety of other functions, but this seems
safe enough.

jim frost
software tool & die
madd@std.com