Get the file descriptor of a socket file. C vs Python.

Hi,

I want to validate that a file is a socket file on Linux. I know I can do this using the S_ISSOCK macro, but I am not sure how to get the file descriptor for the socket file.

For example, I know that /tmp/mapping-foo is a socket file. In Python I can do something like this:

>>> import os
>>> import stat
>>> sb = os.stat('/tmp/mapping-foo')
>>> print stat.S_ISSOCK(sb.st_mode)
True
>>>

How ever in C, I am unable to get the file descriptor for the file /tmp/mapping-foo. I tried using open, fopen and fileno as follows:

        file_des = open("/tmp/mapping-foo", O_RDONLY);
        if( file_des == -1 ) {
                perror("open(2)");
                if((file = fopen("/tmp/mapping-foo", "r")) == NULL ) {
                        perror("fopen()");
                } else {
                        file_des = fileno(file);
                        if (file_des == -1 ) {
                                perror("fileno()");
                        }
                }
                if( file_des == -1 )
                        exit(1);
        }

But, I am getting this error message:

$ ls -l /tmp/mapping-foo
srwxrwxr-x 1 joe joe 0 Jun  9 09:53 /tmp/mapping-foo
$ file /tmp/mapping-foo
/tmp/mapping-foo: socket
$ ./pc /tmp/mapping-foo
Stat file /tmp/mapping-foo
open(2): No such device or address
fopen(): No such device or address

I am trying to load the correct file.

Thanks,
Joe

I seem to have found a working solution: lstat.

        if (lstat("/tmp/mapping-foo", &sbuf) <= -1) {
                perror("lstat()");
        } 

I am still curious to know how to get the file descriptor of a socket file (/tmp/mapping-foo) though.

Thanks again,
Joe

Try something like:
un.sun_family=AF_UNIX;
strcpy(un.sun_path, "(/tmp/mapping-foo");
fd=socket(AF_UNIX,SOCK_STREAM,0);