C语言 如何在网络中广播消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2347416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:38:38  来源:igfitidea点击:

How to broadcast a message in a network?

csocketsnetwork-programming

提问by Zenet

I'm working on a client-server application written in C. I want to broadcast a message to all the machines available on the local network.

我正在开发一个用 C 编写的客户端-服务器应用程序。我想向本地网络上的所有可用机器广播一条消息。

How can I do that using the usual socket system calls in C?

我如何使用 C 中通常的套接字系统调用来做到这一点?

采纳答案by Enrico Carlesso

Just send the message to the broadcast address of your subnet, which for 192.168.0.0/24 is 192.168.0.255, or just broadcast to 255.255.255.255.

只需将消息发送到您子网的广播地址,对于 192.168.0.0/24 来说就是 192.168.0.255,或者只是广播到 255.255.255.255。

回答by Adrien Plisson

you have to use UDP to send a broadcast message over a network. when creating your socket using the socket()function, specify AF_INETfor the familyparameter and SOCK_DGRAMfor the typeparameter. on some systems, you have to enable the sending of broadcast packet by setting the SO_BROADCASTsocket option to 1, using setsockopt().

您必须使用 UDP 通过网络发送广播消息。通过创建套接字时socket()功能,指定AF_INETfamily参数,并SOCK_DGRAMtype参数。在某些系统上,您必须通过将SO_BROADCAST套接字选项设置为 1来启用广播数据包的发送,使用setsockopt().

then use the sendto()function call to send a datagram, and use 255.255.255.255as the destination address. (for datagram sockets, you don't need to call connect(), since there is no 'connection').

然后使用sendto()函数调用发送数据报,并255.255.255.255用作目的地址。(对于数据报套接字,您不需要调用connect(),因为没有“连接”)。

in standard implementations, this address broadcasts to all computer in the local network, this means that the packet will not cross gateway boundaries and will not be received by computers using a network mask diferent from the network mask of the sending computer.

在标准实现中,此地址广播到本地网络中的所有计算机,这意味着数据包不会跨越网关边界,并且不会被使用与发送计算机网络掩码不同的网络掩码的计算机接收。

回答by stefanB

Have a look at udp sockets.

看看 udp 套接字。

I recomend beej guide, have a look at the 6.3 Datagram Sockets

我推荐beej 指南,看看 6.3 Datagram Sockets

回答by RC.

You can use the special address of 255.255.255.255 to send a broadcast message to every computer on the local network.

您可以使用特殊地址 255.255.255.255 向本地网络上的每台计算机发送广播消息。

For more info see section IP Network Broadcasting.

有关更多信息,请参阅IP 网络广播部分。