English 中文(简体)
How to use multicast on a multi-homed system (Java, Linux)
原标题:

This is in Java, but I can always revert to C via JNI if needed.

I have a system with two NICs, each connected to a distinct subnet. I want to use multicast (in particular, SDP) to discover other hosts on both networks.

One network is easy: create a MulticastSocket on the specified port, joinGroup it, and I get packets. Simplicity.

Two networks: so far impossible. I ve tried:

1) creating two sockets, binding to the same port and using setInterface() or setNetworkInterface() to "connect" to the right interface. No luck, even after various permutations of setReuseAddress().

2) create a single socket, and then attempt to join twice, with two calls to joinGroup(SocketAddress mcastaddr, NetworkInterface netIf). The second join call fails.

Solutions outside of Java would be great. In particular, if I could set up multicast routes that would effectively combine the two interfaces (I could then look at each packet to determine which network) that would be fine. As I mentioned before, any amount of native code is usable in this environment (Linux, with the Apache "luni" java infrastructure).

Thanks!

问题回答

Coincidentally, I was working on a similar problem recently.

Here s some Java code which does what you want -- it picks up SDP packets on several interfaces. joinGroup is used to "attach" to the specified interfaces.

/**
 * Demonstrate multi-homed multicast listening
 *
 * usage: java Multihome eth0 eth1 lo <etc>
 */

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

public class Multihome {
    // SDP constants
    public static final String MULTICAST_ADDRESS = "239.255.255.250";
    public static final int MULTICAST_PORT = 1900;

    // args: each arg is the name of an interface.
    public void doMain(Set<String> args)
            throws Exception
    {
        InetSocketAddress socketAddress =
                new InetSocketAddress(MULTICAST_ADDRESS, MULTICAST_PORT);
        MulticastSocket socket = new MulticastSocket(MULTICAST_PORT);
        Enumeration<NetworkInterface> ifs =
                NetworkInterface.getNetworkInterfaces();

        while (ifs.hasMoreElements()) {
            NetworkInterface xface = ifs.nextElement();
            Enumeration<InetAddress> addrs = xface.getInetAddresses();
            String name = xface.getName();

            while (addrs.hasMoreElements()) {
                InetAddress addr = addrs.nextElement();

                System.out.println(name + " ... has addr " + addr);
            }

            if (args.contains(name)) {
                System.out.println("Adding " + name + " to our interface set");
                socket.joinGroup(socketAddress, xface);
            }
        }

        byte[] buffer = new byte[1500];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

        while (true) {
            try {
                packet.setData(buffer, 0, buffer.length);
                socket.receive(packet);
                System.out.println("Received pkt from " + packet.getAddress() +
                                   " of length " + packet.getLength());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
            throws Exception
    {
        Set<String> argSet = new HashSet<String>();
        Multihome multi = new Multihome();

        for (String arg : args) {
            argSet.add(arg);
        }

        multi.doMain(argSet);
    }
}

I d recommend using JGroups, which abstracts everything you re trying to do, if I understand your needs correctly. it s an elegant and well-made framework for multicast (and multicast-like semantics, emulated when necessary).

I have no reasonable setup to try this here, but receiving multicast messages should not require the MulticastSocket to be bound to the port number from the multicast address and setNetworkInterface is used to set the interface used for outbound messages.

What I would try to create two different MulticastSockets (on any free port) and then use joinGroup(SocketAddress mcastaddr, NetworkInterface netIf) on each of them using the same multicast address, but different network interfaces.

Have you considered using ZeroConf for this?

The jmdns project has a pure java implementation which should work very well.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签