通过 Java DatagramSocket 将数据包发送到 255.255.255.255 失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6579350/
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-08-16 07:54:41  来源:igfitidea点击:

Sending packets to 255.255.255.255 by Java DatagramSocket fails

javaudpbroadcastdatagram

提问by Pro.Hessam

I'm programming a networking program in java , and I want to send some Packets to 255.255.255.255, but it fails , even when I send them to 192.168.1.255, which according to the output of ifconfig command , is the broadcast address. But when I send them to my mate's IP it works fine.

我正在用 java 编写一个网络程序,我想发送一些数据包到 255.255.255.255,但它失败了,即使我将它们发送到 192.168.1.255,根据 ifconfig 命令的输出,它是广播地址。但是当我将它们发送到我伙伴的 IP 时,它工作正常。

Here's the code to my program :

这是我的程序的代码:

public class StackOverFlow {
    public static void main(String[] args) {
        Network net= new Network();

        Scanner input= new Scanner(System.in);
        while(input.hasNext())
          net.sendMessage(input.nextLine());
    }
}

I've used DatagarmSocket and DatagramPacket to do so , here's my implementation of the Network :

我使用 DatagarmSocket 和 DatagramPacket 这样做,这是我的网络实现:

class Network {
DatagramSocket socket;

public Network() {
    try {
        socket = new DatagramSocket(8027);
        socket.connect(InetAddress.getByName("255.255.255.255"), 8027);
    } catch (Exception e) {
        System.err.println("Connection failed. " + e.getMessage());
    }
    listen();
}

public void listen() {
    new Thread() {
        public void run() {
            while (true) {
                try {
                    byte[] buf = new byte[1000];
                    DatagramPacket packet = new DatagramPacket(buf,
                            buf.length);
                    socket.receive(packet);
                    String message = new String(buf);
                    System.out.println("Recieved: " + message);
                    if (message.equals("end"))
                        return;
                } catch (Exception e) {
                    System.err.println(e.getMessage());
                }
            }
        }
    }.start();
}

public void sendMessage(String message){
    byte[] buf= message.getBytes();

    DatagramPacket packet= new DatagramPacket(buf, buf.length);
    try{
        socket.send(packet);
    }catch(Exception e){
        System.err.println("Sending failed. " + e.getMessage());
    }
}

No Exceptions are being thrown.
I'm in an ad hoc network.
I'm using MAC OS X 10.6 while my mate is using kubuntu 11.04. And here is ifconfig output:

没有异常被抛出。
我在一个临时网络中。
我使用的是 MAC OS X 10.6,而我的伙伴使用的是 kubuntu 11.04。这是 ifconfig 输出:

lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
inet6 ::1 prefixlen 128 
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 
inet 127.0.0.1 netmask 0xff000000 
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280
stf0: flags=0<> mtu 1280

en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
inet6 fe80::21f:f3ff:fed5:4779%en0 prefixlen 64 scopeid 0x4 
inet 192.168.1.1 netmask 0xffffff00 broadcast 192.168.1.255
ether 00:1f:f3:d5:47:79 
media: autoselect (100baseTX <full-duplex>) status: active
supported media: autoselect 10baseT/UTP <half-duplex> 10baseT/UTP <full-duplex> 10baseT/UTP     <full-duplex,hw-loopback> 10baseT/UTP <full-duplex,flow-control> 100baseTX <half-    duplex> 100baseTX <full-duplex> 100baseTX <full-duplex,hw-loopback> 100baseTX <full-duplex,flow-control> 1000baseT <full-duplex> 1000baseT <full-duplex,hw-loopback> 1000baseT <full-duplex,flow-control> none

en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
inet6 fe80::21d:4fff:feff:2b4d%en1 prefixlen 64 scopeid 0x5 
inet 213.233.170.97 netmask 0xfffffc00 broadcast 213.233.171.255
ether 00:1d:4f:ff:2b:4d 
media: autoselect status: active
supported media: autoselect

fw0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 2030
lladdr 00:21:e9:ff:fe:bc:79:b2 
media: autoselect <full-duplex> status: inactive
supported media: autoselect <full-duplex>

en2: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether 00:1f:f3:b6:2c:be 
media: autoselect status: inactive
supported media: none autoselect 10baseT/UTP <half-duplex>

vmnet1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
inet 192.168.149.1 netmask 0xffffff00 broadcast 192.168.149.255
ether 00:50:56:c0:00:01 

vmnet8: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
inet 192.168.73.1 netmask 0xffffff00 broadcast 192.168.73.255
ether 00:50:56:c0:00:08 

en0 is the device I'm using to connect to my mate.

en0 是我用来连接到我的伴侣的设备。

Please make it simple, I'm a newbie :)

请简单点,我是新手:)

Thanks in advance.

提前致谢。

采纳答案by fyr

While using broadcasting you need to enable it

使用广播时,您需要启用它

socket.setBroadcast(true);

Another thing is that you have to make sure that your router is configured right if the two computers are in two different nets. Broadcasts are usually by default not routed. Further if you have a router having a wirless interface and a wired interface these broadcasts may not work either if broadcasts are not enabled(There may be hardware which forward broadcasts between those two interfaces by default).

另一件事是,如果两台计算机在两个不同的网络中,您必须确保您的路由器配置正确。广播通常默认不路由。此外,如果您有一个具有无线接口和有线接口的路由器,如果未启用广播,这些广播也可能无法工作(默认情况下,可能有硬件在这两个接口之间转发广播)。

回答by Volker Stolz

If I remember correctly, you cannot receive from broadcast-adresses, but only send to them! So on the receiving side, you must be listening on "your" IP specifically.

如果我没记错的话,您不能从广播地址接收,而只能发送给他们!因此,在接收方,您必须专门监听“您的”IP。

回答by Kamahire

192.168.1.255 
  • Please check your subnet mask in your network. It might be possible that your sending machine and the receiving machine are not part of the same network.
  • Please check that the receiving machine exists in your network.
  • If there's a router in between your machines, I don't think the message will be transmitted.
  • 请检查您网络中的子网掩码。您的发送机器和接收机器可能不是同一网络的一部分。
  • 请检查接收机器是否存在于您的网络中。
  • 如果您的机器之间有路由器,我认为不会传输消息。

回答by captainroxors

Rather than connect your DatagramSocket to the broadcast address, just construct the DatagramPacket to target it, i.e.

而不是将您的 DatagramSocket 连接到广播地址,只需构造 DatagramPacket 来定位它,即

DatagramPacket dp = new DatagramPacket(byteArray, byteArray.length, InetAddress.getByName("255.255.255.255"), yourPortNumber);

And like magic, you've sent a broadcast. And then to catch it on the other side, just have that end listening on that port:

就像魔术一样,你发送了一个广播。然后在另一端捕获它,只需让该端侦听该端口:

DatagramSocket dsock = new DatagramSocket(samePortUsedAbove);
DatagramPacket dp = new DatagramPacket(byteArray, byteArray.length);
dsock.receive(dp);