0

I'm writing a java program which needs to get the computer's IP address(not the Internet IP, just the local one). The program worked, but when I connected to my VPN server, I noticed that the IP address I was getting was invalid. This is the code I'm using:

public static String getIP() {

    try (final DatagramSocket socket = new DatagramSocket()) {
        socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
        return socket.getLocalAddress().getHostAddress();
    } catch (IOException ex) {
        ErrorHandler.handle(ex);
        return "";
    }
}
Xyz
  • 212
  • 2
  • 9
  • The code looks like it was taken from [`here`](https://stackoverflow.com/questions/9481865/getting-the-ip-address-of-the-current-machine-using-java) did you try the other answers (e.g. `InetAddress.getLocalHost()`) ? – second Aug 21 '19 at 08:30
  • `InetAddress.getLocalHost()` returns my loopback address(127.0.0.1), and I'm trying to get my local network IP (e.g. 192.168.1.120) – Xyz Aug 21 '19 at 08:37
  • Then you have to loop through the NetworkInterfaces (as described in the answer). I am sure its in there, the problem is identifying the correct one. – second Aug 21 '19 at 08:41

0 Answers0