Semaphor
Semaphor

Reputation: 1040

Binding Socket to any existing address on specific subnet

I have a java application in which I want to receive a udp broadcast telegram in a known subnet, for example 192.168.x.x (255.255.0.0). If I know the IP of the machine which is running the application, the following works (assuming the IP of the machine is 192.168.10.1)

InetAddress ip = InetAddress.getByName("192.168.10.1");
DatagramSocket socket = new DatagramSocket(2222, ip);

But if the IP is not fix, maybe from a dhcp server, how could I create a socket which is bounded to the ip which the machine gets from the dhcp server. There may be other interfaces on other subnets, so if I will use

DatagramSocket socket = new DatagramSocket(2222);

the socket is not surely bounded to the ip in the subnet with 192.168.x.x.

How could I solve this?

Upvotes: 2

Views: 426

Answers (1)

user43968
user43968

Reputation: 2129

So if I understand your problem is to get the address assigned to an interface. I suppose you have more than one interface and you want to select one.

Also note by using DatagramSocket socket = new DatagramSocket(2222); you are binding to the wildcard address that often mean any and should work in many cases

From Oracle documentation List Network interfaces you can retrieve inetAddress from different interfaces

import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
        out.printf("\n");
     }
}  

Upvotes: 1

Related Questions