Bionix1441
Bionix1441

Reputation: 2319

Determine if a descriptor is a socket or a regular file on windows?

I have read this post Determine between socket and fd, and the answer recommends creating a structure with two fields, is there another way to test if a descriptor is a socket or a regular file on windows ?

Upvotes: 0

Views: 627

Answers (2)

Andreas Otto
Andreas Otto

Reputation: 329

this could help:

replace stdin stdout stderr with a socket…

http://www6.uniovi.es/cscene/CS5/CS5-05.html

int exec_comm_handler( int sck )
{
  close(0); /* close standard input  */
  close(1); /* close standard output */
  close(2); /* close standard error  */

  if( dup(sck) != 0 || dup(sck) != 1 || dup(sck) != 2 ) {
    perror("error duplicating socket for stdin/stdout/stderr");
    exit(1);
  }

  printf("this should now go across the socket...\n");
  execl( "/bin/sh", "/bin/sh", "-c", "/path/to/redirected_program" );
  perror("the execl(3) call failed.");
  exit(1);
}

Our 'comm handler' first closes the file descriptors for standard input, standard output, and standard error. It then uses dup(2) to duplicate the socket file handle. dup(2) will duplicate the given file descriptor and return the duplicate as the next available descriptor. Since 0, 1, and 2 are the next available descriptors, they should be the returned duplicates. Now operations on stdin/stdout/stderr [0/1/2] will act upon the socket instead of the original stdin/stdout/stderr.

I was unaware that this technique (calling dup(2) on a socket file descriptor) was possible untill seeing code written by Martin Mares.

Upvotes: 0

user207421
user207421

Reputation: 310850

You could try something that should only work on a socket, and see if it fails with ENOTSOCK. getsockname() for example.

Upvotes: 1

Related Questions