3

I was trying to make a jFrame which had a button & a text-area/label, the motive being able to retrieve my systems IP Address, the problem is, when I use this code

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try
        {
            InetAddress ownIP=InetAddress.getLocalHost();
            jTextField1.setText(ownIP.getHostAddress());
        }
        catch (Exception e)
        {
            jTextField1.setText(e.getMessage());
        }
    }

But then this gives me back the loop back IP Address, 127.0.0.1 :( I have static IP configured on my system, but then too that IP does not show up I use NetBeans IDE 7.0 & Ubuntu 11.04

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
Roshan
  • 2,604
  • 2
  • 15
  • 13

2 Answers2

4

You can obtain all IP addresses for your system. Use the NetworkInterface.getNetworkInterfaces() method to retrieve all of the network interfaces. For each of the returned interfaces, use the getInetAddresses() method to retrieve all of the associated addresses.

Brandon E Taylor
  • 24,881
  • 6
  • 47
  • 71
  • You probably either want `wlan0` or `eth0`. `lo` refers to loopback. – Christian Mann Aug 01 '11 at 03:07
  • 1
    You could filter out loopback by using the isLoopback() method. If you run both IPv4 and IPv6, you might also want to filter one or the other out by checking the type of InetAddress against Inet4Address or Inet6Address. – prunge Aug 01 '11 at 04:34
2

FWIW, InetAddress.getLocalHost().getHostAddress() gives me my real ip address.

FYI, I ran it from a unit test within Eclipse on a macbook.

Bohemian
  • 412,405
  • 93
  • 575
  • 722