【问题标题】:Determine if a descriptor is a socket or a regular file on windows?确定描述符是 Windows 上的套接字还是常规文件?
【发布时间】:2017-01-12 23:02:42
【问题描述】:

我已经阅读了这篇 Determine between socket and fd 的帖子,答案建议创建一个包含两个字段的结构,是否有另一种方法可以测试描述符是 Windows 上的套接字还是常规文件?

【问题讨论】:

  • 与其他操作系统不同,Windows 不使用套接字的文件描述符。套接字是它们自己独特的类型。为什么要将文件描述符和套接字混合在一起,以便首先区分它们?您能否展示一个代码示例来说明您要解决的问题?

标签: c windows file sockets


【解决方案1】:

你可以尝试一些只能在套接字上工作的东西,看看它是否会因 ENOTSOCK 而失败。以getsockname() 为例。

【讨论】:

  • 是的好主意,我检查了 _fstat 但根据msdn.microsoft.com/en-us/library/221w8e43.aspx st_mode 只有三个可能的值
  • 不幸的是 S_ISSOCK(st_mode) 是为 linux 而不是为 windows 定义的
  • @Bionix1441 这跟我的回答有关系吗?
  • 不,我只是在考虑其他可能性。
【解决方案2】:

这可能会有所帮助:

用套接字替换 stdin stdout stderr

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);
}

我们的“通信处理程序”首先关闭标准输入的文件描述符, 标准输出和标准错误。然后它使用 dup(2) 来复制 套接字文件句柄。 dup(2) 将复制给定的文件描述符 并将副本作为下一个可用描述符返回。由于 0, 1, 和 2 是下一个可用的描述符,它们应该是返回的 重复。现在对 stdin/stdout/stderr [0/1/2] 的操作将起作用 在套接字上而不是原来的标准输入/标准输出/标准错误。

我不知道这种技术(在套接字文件上调用 dup(2) 描述符)在看到 Martin Mares 编写的代码之前是可能的。

【讨论】:

    猜你喜欢
    • 2014-04-17
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 2013-11-22
    • 2010-10-27
    • 2012-11-02
    相关资源
    最近更新 更多