有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中忽略自己的UDP广播的网络编程

在我的程序中,我发送UDP广播并对其做出反应。我需要一种方法来忽略发出的UDP广播,但对不是来自我的机器的广播做出反应

我试过使用: if (NetworkInterface.getByInetAddress(packet.getAddress()) != null) 但在某些情况下,这会产生IOException(java.net.SocketException:没有网络接口绑定到这样的IP地址)

有人有什么想法吗

此外: socket上的getInetAddress()抛出NullPointerException


共 (4) 个答案

  1. # 1 楼答案

    当然,解决这个问题的“工业实力”解决方案是为每个服务器生成一个随机UUID,并在每个数据包中包含这个ID(可能是int或long)。如果这个ID和你的匹配,你可以放弃它

    我不喜欢这个解决方案,因为它会在每个数据包中浪费大量字节。但它简单有效

  2. # 2 楼答案

    这并不是你问题的答案。但对于处理UDP广播,您应该看看JGroups

    JGroups is a toolkit for reliable multicast communication. (Note that this doesn't necessarily mean IP Multicast, JGroups can also use transports such as TCP). It can be used to create groups of processes whose members can send messages to each other. The main features include

    • Group creation and deletion. Group members can be spread across LANs or WANs
    • Joining and leaving of groups
    • Membership detection and notification about joined/left/crashed members
    • Detection and removal of crashed members
    • Sending and receiving of member-to-group messages (point-to-multipoint)
    • Sending and receiving of member-to-member messages (point-to-point)
  3. # 3 楼答案

    我认为javadoc和NetworkInterface getByInetAddress()的实际实现之间存在一些差异。javadoc似乎暗示,如果没有找到匹配项,getByInetAddress将返回null,但实现要么返回匹配项,要么抛出SocketException

    JavaDoc

    public static NetworkInterface getByInetAddress(InetAddress addr)
                                                   throws SocketException
    

    返回:NetworkInterface,如果没有指定IP地址的网络接口,则返回null

    实施

      public static NetworkInterface getByInetAddress (InetAddress addr)
        throws SocketException
      {
        if (networkInterfaces == null)
          networkInterfaces = getRealNetworkInterfaces ();
    
        for (Enumeration interfaces = networkInterfaces.elements ();
             interfaces.hasMoreElements (); )
          {
            NetworkInterface tmp = (NetworkInterface) interfaces.nextElement ();
    
            for (Enumeration addresses = tmp.inetAddresses.elements ();
                 addresses.hasMoreElements (); )
              {
                if (addr.equals ((InetAddress) addresses.nextElement ()))
                  return tmp;
              }
          }
    
        throw new SocketException (
          "no network interface is bound to such an IP address");
      }
    

    我建议要么捕获异常并将其视为来自第三方的答案,要么使用getNetworkInterfaces()方法重新实现它

  4. # 4 楼答案

    你不能为你自己的主机做一个equals()介于packet.getAddress()之间的Address对象吗