JAVA installs / selects a specific network card from several (UDP)

I am trying to send UDP with a datagram to JAVA, and my machine has several network adapters with different IP addresses.

How can I establish which network adapter I want to send from my package? (assuming I have more than one in my car?)

EDIT I

I do not use Socket, I use DatagramSocket and try to bind like this:

/*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 this, I can no longer connect (or cannot receive the packet ..). The problem is that I have 2 network adapters, but one for the INTERNAL network, and the other for the Internet. I need all the data on my server to be accessible only in the INTERNAL machine.

EDIT II

To clarify. This application is a server - and SERVER has 2 NICS. one LAN and one for WAN.

An alternative way for me - to specify ROUTING in some way - means to tell each packet which network adapter to use.

How to make such routing in JAVA ??

+6
source share
4 answers

The Socket class has a constructor that takes a localAddr argument. Can this be applicable to you?

Edit: 1) Do not route in Java, leave it in the OS.

2) I hope you have visited Everything about datagrams ?

3) The server can bind to 0.0.0.0 (that is, to any IP address on the machine), which happens if you specify only a port in the DatagramSocket constructor or you can bind to a specific interface if you select DatagramSocket(int port, InetAddress laddr) constructor is what you should do!

4) Then the client sends everything that it needs to send, and the server can respond using the socket created in 3) and destination.getAddress () / packet.getPort ().

Greetings

+2
source

I had the same problem with you. It didn’t solve the problem right away, but finally I wrote some code that might be useful to 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 make sure the code is working correctly, and it seems like it is being done, I am still working on it, but I suppose this might be enough for your problem.

+2
source

From the docs tutorial Here , “To send data, the system determines which interface is used. However, if you have a preference or not need to specify which network adapter to use, you can query the system for the corresponding interfaces and find the address on the interface that you want use".

NetworkInterFaces software can be accessed programmatically, for example,
Enumeration en = NetworkInterface.getNetworkInterfaces ();

Iterating over each, you can associate an InetAddress associated with it and use InetAddress to create a datagram socket.
There is good information in this question - How to list the IP addresses of all allowed NICs with Java?

hope this helps

+1
source

Here is basically the complete code I used. In my case, I know the IP address prefix used by my connection. You may need to look for the interface name and compare it with the value that you store in the configuration file.

Note the use of MulticastSocket instead of DatagramSocket, so the setNetworkInterface method is available to bind the required interface. Since MulticastSocket is a child of the DatagramSocket class, a switch usually does not cause problems.

 @Override public void connect() throws InterruptedException { NetworkInterface iFace; iFace = findNetworkInterface(); connectControlBoard(iFace); connectUTBoards(iFace); }//end of Capulin1::connect //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Capulin1:findNetworkInterface // // Finds the network interface for communication with the remotes. Returns // null if no suitable interface found. // // The first interface which is connected and has an IP address beginning with // 169.254.*.* is returned. // // NOTE: If more than one interface is connected and has a 169.254.*.* // IP address, the first one in the list will be returned. Will need to add // code to further differentiate the interfaces if such a set up is to be // used. Internet connections will typically not have such an IP address, so // a second interface connected to the Internet will not cause a problem with // the existing code. // // If a network interface is not specified for the connection, Java will // choose the first one it finds. The TCP/IP protocol seems to work even if // the wrong interface is chosen. However, the UDP broadcasts for wake up calls // will not work unless the socket is bound to the appropriate interface. // // If multiple interface adapters are present, enabled, and running (such as // an Internet connection), it can cause the UDP broadcasts to fail. // public NetworkInterface findNetworkInterface() { logger.logMessage(""); NetworkInterface iFace = null; try{ logger.logMessage("Full list of Network Interfaces:" + "\n"); for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); logger.logMessage(" " + intf.getName() + " " + intf.getDisplayName() + "\n"); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { String ipAddr = enumIpAddr.nextElement().toString(); logger.logMessage(" " + ipAddr + "\n"); if(ipAddr.startsWith("/169.254")){ iFace = intf; logger.logMessage("==>> Binding to this adapter...\n"); } } } } catch (SocketException e) { logger.logMessage(" (error retrieving network interface list)" + "\n"); } return(iFace); }//end of Capulin1::findNetworkInterface //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Capulin1::connectControlBoards // public void connectControlBoard(NetworkInterface pNetworkInterface) throws InterruptedException { logger.logMessage("Broadcasting greeting to all Control boards...\n"); MulticastSocket socket; try{ socket = new MulticastSocket(4445); if (pNetworkInterface != null) { try{ socket.setNetworkInterface(pNetworkInterface); }catch (IOException e) {}//let system bind to default interface } } catch (IOException e) { logSevere(e.getMessage() + " - Error: 204"); logger.logMessage("Couldn't create Control broadcast socket.\n"); return; } ...use the socket here... 
0
source

Source: https://habr.com/ru/post/927014/


All Articles