4

OS X 不提供SO_PROTOCOL允许调用者“...以整数形式检索套接字类型”的套接字选项。(http://linux.die.net/man/7/socket

换句话说,以下程序在 linux 下构建并运行,但在 OS X 下无法编译:

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char **argv)
{
    int c, s, type, len;
    len = sizeof(type);

    s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s < 0)
    {  
        fprintf(stderr, "socket kaboom: %s\n", strerror(errno));
        return 1;
    }
    if (getsockopt(s, SOL_SOCKET, SO_PROTOCOL, &type, &len) < 0)
    {  
        fprintf(stderr, "getsosockopt kaboom: %s\n", strerror(errno));
        return 1;
    }
    printf("socket type: %d\n", type);
    return 0;
}

如何在 OS X 下做到这一点?

4

1 回答 1

2

标准的SO_TYPE套接字选项,它返回像SOCK_STREAM(对应于 TCP)和SOCK_DGRAM(对应于 UDP)这样的值,就足够了。使用 SCTP,SOCK_STREAM可能对应于 TCP 或 SCTP,SO_PROTOCOL有助于区分它们,但 MacOS X 不支持 SCTP。

Unix 域套接字不使用协议号;因此,SO_TYPE在那里也是正确的选择。

于 2014-06-26T22:10:49.107 回答