2010-07-15

Get reliable local IP address in Java 6

It is strange: I consider myself still being new to Java, but when I search for particular sample code, that should be written thousand times before, I sometimes find only samples that do only half the job or miss important details.
So happened for getting the local IP address(es) of the machine you are running on. I experienced for example performance issues retrieving the IPs when running with a mobile internet stick (point-to-point device).

My example code can be found here: http://pastebin.com/5X073pUc

If you want just one address, that is probably the best fitting then you probable want to use this example: http://pastebin.com/PLAcTXac

Related post: Dynamic method invocation in Java 6.

6 comments:

Alexander Zagniotov said...

Thanks Martin,

This is very useful :)

Shellback3 said...

This is useful to me, too.
In the "catch" this line appears:
Logger.getLogger(Net.class.getName()).log(Level.WARNING,

What is Net? Eclipse Indigo chokes on it.

Thanks
Nate

Martin Wildam said...

Net is just the main class file where I put the function in. Replace it with the class name where the function is contained in in your case.

Henry Zheng said...

The solution you provide is good, but it's not right in some cases, especially when there are virtual interfaces. You can refer to this post for more details: http://ireasoning.com/articles/find_local_ip_address.htm

Martin Wildam said...

Thank you very much for your feedback.
I tested my function on a Windows 2008r2 virtual machine and in fact the resulting IP address was not the one I would have desired to get.

However, using route print I get even different output than you - I even get two default routes - what a pitty!

Fortunately after the initial routes listed there is a second section entitled "Persistent routes" - there finally there is only one default route.

I did not test your code yet - just had a short look, but I imagine under these circumstances your code does not return the correct IP either because you return on first found default route as far as I have read from your code.

When I have more time I will try to make it work everywhere. Unfortunately who knows how the output is on a mac or on solaris - that's because I usually try to avoid using a solution that has to distinguish and behave differently on different platforms (hack - that's the reason, why Java is my favorite language - because I don't have to bother in most cases ;-) ).

Anonymous said...

great martin. many thanks for the contribution!