简体   繁体   English

Java DatagramChannel组播默认为IPv6

[英]Java DatagramChannel Multicast Defaults to IPv6

I'm trying to write an abstract class that will be inherited by three classes: 我正在尝试编写一个将由三个类继承的抽象类:

  • UDPServer UDP服务器
  • MulticastServer 组播服务器
  • TCPServer TCP服务器

MulticastServer is the only one with which I am having issues. MulticastServer是我遇到的唯一问题。 As of now, it is UDP only. 到目前为止,它仅是UDP。 When a connection is received, I would like it to hand the socket to a predefined Consumer<*SocketType*> stored in the member m_handler . 接收到连接后,我希望它将套接字传递给存储在成员m_handler的预定义的Consumer<*SocketType*> m_handler Consumer<*SocketType*> I'm using a Selector to do this. 我正在使用Selector来执行此操作。

The main issue I'm running into at this time is that it seems to default to IPv6. 我目前遇到的主要问题是它似乎默认为IPv6。 I'm getting the message: 我收到消息:

java.lang.IllegalArgumentException: IPv6 socket cannot join IPv4 multicast group java.lang.IllegalArgumentException:IPv6套接字无法加入IPv4组播组

// m_chan is a member instance of the channel type. DatagramChannel for multicast.

if(tcpmode) // true if the generic socket type passed is ServerSocket
    ((ServerSocketChannel)m_chan).socket().bind(sa);
else{
    if(multicast) // true if the generic socket type passed is MulticastSocket
        ((DatagramChannel)m_chan).join(Inet4Address.getByName(m_host), getIPAddr());
    else
        ((DatagramChannel)m_chan).socket().bind(sa);
}

And here is the code for getIPAddr() : 这是getIPAddr()的代码:

static NetworkInterface getIPAddr() throws SocketException, UnknownHostException{   
    InetAddress iaddr = InetAddress.getLocalHost();     
    NetworkInterface iface = NetworkInterface.getByInetAddress(iaddr);
    return iface;
}

I've tried adding this: 我尝试添加以下内容:

System.setProperty("java.net.preferIPv4Stack" , "true");

to no avail. 无济于事。

I'm definitely using IPv4. 我肯定在使用IPv4。

The following works fine for me. 以下对我来说很好用。 I only get the same exception you describe, when I change the StandardProtocolFamily.INET to StandardProtocolFamily.INET6, so I assume you somehow used the wrong option when creating the DatagramChannel? 当我将StandardProtocolFamily.INET更改为StandardProtocolFamily.INET6时,我只会得到与您描述的异常相同的异常,因此我假设您在创建DatagramChannel时以某种方式使用了错误的选项?

public class Test {
    public static void main(String[] args) throws IOException {
        NetworkInterface ni = NetworkInterface.getNetworkInterfaces().nextElement();
        DatagramChannel server = DatagramChannel.open(StandardProtocolFamily.INET)
            .setOption(StandardSocketOptions.SO_REUSEADDR, true)
            .bind(new InetSocketAddress(5000))
            .setOption(StandardSocketOptions.IP_MULTICAST_IF, ni);
        server.join(Inet4Address.getByName("225.4.5.6"), ni);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM