OSX上的UDP广播失败,但在Linux上工作
以下代码在OSX上不起作用(在Linux上可以正常工作);它(绑定)失败,errno = 49 无法分配请求的地址
。
int fd, val;
struct sockaddr_in sa;
fd = socket(AF_INET, SOCK_DGRAM, 0);
if(fd < 0)
return -1;
val = 1;
if(setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val)) < 0)
goto exit;
memset(&sa, 0, sizeof(sa));
sa.sin_len = sizeof(sa);
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(INADDR_BROADCAST);
sa.sin_port = htons(50000);
if(bind(fd, (struct sockaddr *)&sa, sizeof(sa)))
goto exit;
如果您指定了inaddr_broadcast
(或者,至少inaddr_any
工作正常),则该代码确实可以在OSX上使用。我发现Darwin具有Linux没有的sin_len
字段,但是设置或清除它没有效果。
知道有什么麻烦?如果它与MACF有关,我觉得它似乎会返回与安全有关的错误。
总体而言,很少有OSX的示例来源,我找不到UDP广播的任何示例。
似乎甚至socat
无法在OSX上正确执行此操作。顺便说一句,它以相同的方式失败,同样的错误。
$ echo "TEST" | socat - UDP-DATAGRAM:255.255.255.255:50000,broadcast
2022/06/13 22:39:16 socat[7349] E sendto(5, 0x14100c000, 17, 0, LEN=16 AF=2 255.255.255.255: 50000, 16): Can't assign requested address
The following code does not work on OSX (it works fine on Linux); it (bind) fails with errno=49 Can't assign requested address
.
int fd, val;
struct sockaddr_in sa;
fd = socket(AF_INET, SOCK_DGRAM, 0);
if(fd < 0)
return -1;
val = 1;
if(setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val)) < 0)
goto exit;
memset(&sa, 0, sizeof(sa));
sa.sin_len = sizeof(sa);
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(INADDR_BROADCAST);
sa.sin_port = htons(50000);
if(bind(fd, (struct sockaddr *)&sa, sizeof(sa)))
goto exit;
This bit of code does work on OSX if you specify an actual address other than INADDR_BROADCAST
(or, at least INADDR_ANY
works fine). I found that Darwin has this sin_len
field that Linux does not, but setting or leaving it cleared has no effect.
Any idea what could be the trouble? If it were related to MACF I feel as if it would return a security-related error.
There are few example sources for OSX in general, and I did not find any for UDP broadcast.
It seems even socat
can't do this properly on OSX. Incidentally it failed in the same way with the same error.
$ echo "TEST" | socat - UDP-DATAGRAM:255.255.255.255:50000,broadcast
2022/06/13 22:39:16 socat[7349] E sendto(5, 0x14100c000, 17, 0, LEN=16 AF=2 255.255.255.255: 50000, 16): Can't assign requested address
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论