Your daily dose of Java and related technologies.
News, Releases, Reviews, Tutorials, Articles, Events, Contests, Comments, Code and much more.
This java weblog is maintained by Xyling Technologies, making life simpler.

Saturday, October 07, 2006

Getting all IP addresses of local machine

This is one code that saved hours for me. Thanks to "jguru" for sharing the code that gives me all the IP addresses associated with my system.

Simply calling InetAddress.getLocalHost().getHostAddress() cannot solve the problem as it may return only one IP address.

        Enumeration addrs = ni.getInetAddresses();

while (addrs.hasMoreElements()) {
InetAddress ia = (InetAddress)addrs.nextElement();
System.out.println(" " + ia.getHostAddress());
}


The code (point to the title of this post) gives you the IP address of all your network connections including your public IP that is created when you connect to internet.

[Resource-Type: Source Code; Category: J2EE, J2SE; XRating: 5]

3 Comments:

Anonymous Tim Fennell said...

Don't you love though that this throws a /checked/ exception: UnknownHostException. I guess this makes sense in J2ME or some other restricted environment, but sheesh.

3:21 PM

 
Blogger Xyling Technologies said...

Hi Tim,

Yes, It does make sense in J2ME but this code helped me in some other way in my day to day use.

Here's how it helps me.

Sometimes, I need to access my home PC (which is almost always ON) from outside. But the IP address allocated by my services provider is dynamic. Now, till the time I do not know this IP address, I cannot connect my home PC. So I use this code to find the latest IP on my system and use JavaMail API to send me a mail whenever there is a change in IP.

Hows the idea? ;)

9:23 AM

 
Anonymous Charles Kubicek said...

Perhaps a better solution (if your router supports it).

http://www.dyndns.com/services/dns/dyndns/

10:10 AM

 

Post a Comment

<< Home