问题描述
在我的程序中,我发送UDP广播并对它们作出反应。我需要一种方法来忽略我发送的UDP广播,但对那些不是来自我的机器的广播做出反应。
In my program I'm sending out UDP broadcasts and reacting to them. I need a way to ignore the UDP broadcasts that I send out, but react to ones that aren't from my machine.
我做了尝试使用:
if(NetworkInterface.getByInetAddress(packet.getAddress())!= null)
但在某些情况下这会生成IOExceptions(java。 net.SocketException:没有网络接口绑定到这样的IP地址)
I did try using:if (NetworkInterface.getByInetAddress(packet.getAddress()) != null)
but this generated IOExceptions in some cases (java.net.SocketException: no network interface is bound to such an IP address)
任何想法?
:我的套接字上的
getInetAddress()抛出一个NullPointerException
Also:getInetAddress() on my socket throws a NullPointerException
推荐答案
我认为javadoc与之间存在一点差异实际实现 NetworkInterface getByInetAddress()
。 javadoc似乎暗示如果没有找到匹配,getByInetAddress将返回null,但实现要么返回匹配,要么抛出SocketException。
I think there's a little discrepancy between the javadoc and the actual implementation of NetworkInterface getByInetAddress()
. The javadoc seems to suggest that getByInetAddress would return null if no match was found, yet the implementation either returns a match, either throws a SocketException.
public static NetworkInterface getByInetAddress(InetAddress addr)
throws SocketException
返回:如果没有指定IP地址的网络接口,则返回NetworkInterface或 null。
Returns: A NetworkInterface or null if there is no network interface with the specified IP address.
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");
}
我建议要么抓住异常并将其视为第3个答案派对,要么使用 getNetworkInterfaces()
方法重新实现它。
I suggest to either catch the exception and treat it as an answer from a 3rd party, either re-implement it using the getNetworkInterfaces()
method.
这篇关于在Java中忽略您自己的UDP广播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!