例如,linux内核-2.6.32-279没有在/usr/include/asm中定义SO_REUSEPORT -泛型/socket.h,但是内核-2.6.32-431定义了它。
那么如果我构建一些代码,比如:
#include <sys/socket.h>
#include <unistd.h>
int createsock()
{
int sock = socket(AF_INET, SOCK_DGRAM, 0);
#ifdef SO_REUSEPORT
int reuse = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT,(const char*)&reuse, sizeof(reuse)) < 0)
{
close(sock);
return -1;
}
#endif
return sock;
}用内核构建的可执行文件-2.6.32-431,它正确地工作在内核-2.6.32-431,但不适用于内核-2.6.32-279。如果它是用内核-2.6.32-279构建的,那么这两者都能工作。
此代码在构建时检测选项可用性,并且在运行时可能会有所不同。
什么是在运行时检测的方法?
发布于 2014-01-30 11:18:03
当setsockopt调用失败时,您可以检查errno,看看哪里出错了。如果是EINVAL或ENOPROTOOPT,则套接字选项无效,您将继续进行其他操作。
如果您担心可能发生什么事情,请先调用getsockopt,如果errno失败,则以相同的方式检查它。
发布于 2014-01-30 11:18:11
getsockopt呢?曼佩奇
使用getsockopt,您可以检查[ENOPROTOOPT] The option is unknown at the level indicated的返回代码。而不触及选择。
在这篇文章中:
The following options are recognized at the socket level. Except as
noted, **each may be examined with getsockopt()** and set with setsockopt().
(...)
SO_REUSEPORT enables duplicate address and port bindings
(...)https://stackoverflow.com/questions/21454879
复制相似问题