JAVA set / choose specific NIC from multiple (UDP)

user1722362 picture user1722362 · Oct 5, 2012 · Viewed 12k times · Source

I am trying to send UDP with datagram in JAVA and my machine have several NIC with different IP's.

How can I set which NIC I want my packet to be sent from ?? (assuming I have more than one on the machine ??)

EDIT I

I am not using Socket, I am using DatagramSocket and tried to do binding like so:

/*binding */
        DatagramSocket ds = new DatagramSocket(1111);
        NetworkInterface nif = NetworkInterface.getByIndex(nicIndex);
        Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
        ds.bind(new InetSocketAddress(nifAddresses.nextElement(), 0));

But when I do so, I can not connect anymore (or can not get the packet ..). The problem is that I have 2 NIC, but one is for INTERNAL network and the other one is for Internet .. I need all my server data to go only on the INTERNAL one..

EDIT II

For Clarification . This App is a server - and the SERVER has 2 NICS . one LAN and one for WAN.

An alternative way for me would to specify a ROUTING somehow - meaning to tell each packet exactly which NIC to use ..

How to do such a routing in JAVA ??

Answer

Niles picture Niles · Jan 30, 2015

I just had the same problem of you. It was not immediate to solve the problem but finally I wrote some code that can be useful for you:

//set Network Interface
        NetworkInterface nif = NetworkInterface.getByName("tun0");
        if(nif==null){
            System.err.println("Error getting the Network Interface");
            return;
        }
        System.out.println("Preparing to using the interface: "+nif.getName());
        Enumeration<InetAddress> nifAddresses = nif.getInetAddresses();
        InetSocketAddress inetAddr= new InetSocketAddress(nifAddresses.nextElement(),0);

        //socket.bind(new InetSocketAddress(nifAddresses.nextElement(), 0));
        DatagramSocket socket = new DatagramSocket(inetAddr);
        System.out.println("Interface setted");

I used a lot of output to be sure that the code is working properly and it look like to do it, I am still working on it but I suppose this can be enough for your problem