tags:

views:

211

answers:

5

Could the socket function call in C return 0 or 1 as the value for the socket descriptor?

   int socket(int domain, int type, int protocol);

According to the man page I have:

RETURN VALUE
   -1 is returned if an error occurs; otherwise the  return  value  is  a
   descriptor referencing the socket.

It seems like it could, or at least the man page makes no mention of any reserved values. Is it written somewhere else that valid socket descriptors need to be 2 or greater?

I'm specifically running on a linux 2.4.22 kernel, but I'm curious to know for any unix based implementation of socket.

A: 

According to the man page, yes, it could.

Paul Nathan
+5  A: 

Both 0 and 1 are valid return vales, and might indeed be returned if the application has closed its standard input or output file descriptors.

anon
+1  A: 

When your process starts, 0 is stdin and 1 is stdout, but you can close them, and therefore, you could get these FD back

Zorglub
+1  A: 

0 or 1 will precisely come if you have closed the stdin or stdout descriptors. This could be happening, because by mistake you might be passing a variable (most probably the one in which you store your socket descriptor) to the socket closing function after initialization. Since the variable might be initialized to 0, it might cause closure of stdin.

Jay
+2  A: 

The only values that are not valid file descriptors are those less than 0. -1 will indicate an error and errno will be set. You shouldn't ever see a negative value that is not -1.

CaptnCraig