Alex Rivera | Logout

Determine between socket and fd

Asked 2011-06-23T22:12:02.590
15

On unix everything is a file approach of function read(), write(), close() is not supported on Win32.

I want to emulate it but have no idea how to distinguish when sock is socket or fd on WinSocks2.

//returns 1 if `sock` is network socket, 
//        0 if `sock` is file desriptor (including stdio, stderr, stdout), ...
//       -1 in none of above
int is_net_socket(int sock)
{
    // ...?
}

This should work as in :

int mysock  = socket(PF_INET, SOCK_STREAM, 0);
int myfd    = _open("my_file.txt", _O_RDONLY);

printf("1: %d    2: %d    3: %d    4:%d\n",
       is_net_socket(mysock),   //1
       is_net_socket(myfd),     //0
       is_net_socket(stdin),    //0
       is_net_socket(stderr));  //0

// should print "1: 1    2: 0    3: 0    4:0"

How to implement is_net_socket in order to use it as in:

int my_close(int sock)
{
#if ON_WINDOWS
    switch( is_net_socket(sock) ) {
        case 1: return closesocket(sock);
        case 0: return _close(sock);
        default: //handle error...
    }
#else
    return close(sock);
#endif
}
Edit
Report

1 Answer

3

I suspect... but I am not sure, that fds and sockets on Windows use separate namespaces. Therefore the number for a socket and a file could be the same, and it is impossible to know which one you are talking about when you call is_net_socket.

Try printing out socket and fd numbers to see if they are ever the same as each other at the same time.

answered 2011-06-23T22:47:12.413

Your Answer