Class for determining a host's IP address. : NetworkInterface « Network Protocol « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JDK 6
25.JNDI LDAP
26.JPA
27.JSP
28.JSTL
29.Language Basics
30.Network Protocol
31.PDF RTF
32.Reflection
33.Regular Expressions
34.Scripting
35.Security
36.Servlets
37.Spring
38.Swing Components
39.Swing JFC
40.SWT JFace Eclipse
41.Threads
42.Tiny Application
43.Velocity
44.Web Services SOA
45.XML
Java » Network Protocol » NetworkInterfaceScreenshots 
Class for determining a host's IP address.
    
/**
 * Copyright (c) 2006 Richard Rodgers
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//package com.monad.homerun.util;

import java.net.InetAddress;
import java.net.Inet6Address;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/*
 * Class for determining a host's IP address.
 * Uses several techniques to circumvent OS-specific problems in
 * specific calls. For example, 'getLocalHost()' on Linux tends to
 * return only the loopback address (bug, security?), but not on Windows.
 */

public class LocalAddress
{    
  /**
   * Return an address of a non-loopback interface on the local host
   
   @return address
   *         the InetAddress of the local host
   */
  public static InetAddress getLocalAddress()
  {
    InetAddress addr = null;    
    try
    {
      addr = InetAddress.getLocalHost();
      // OK - is this the loopback addr ?
      if ! addr.isLoopbackAddress() )
      {
        return addr;
      }
      // plan B - enumerate the network interfaces
      Enumeration ifaces = NetworkInterface.getNetworkInterfaces();
      whileifaces.hasMoreElements() )
      {
        NetworkInterface netIf = (NetworkInterface)ifaces.nextElement();
        Enumeration addrs = netIf.getInetAddresses();
        whileaddrs.hasMoreElements() )
        {
          addr = (InetAddress)addrs.nextElement();
          //System.out.println( "enum: " + addr.getHostAddress() );
          if addr instanceof Inet6Address )
          {
            // probably not what we want - keep looking
            continue;
          }
          // chose (arbitrarily?) first non-loopback addr
          if ! addr.isLoopbackAddress() )
          {
            return addr;
          }
        }
      }
      // nothing so far - last resort
      return getReflectedAddress();
    }
    catch UnknownHostException uhE )
    {
      // deal with this
    }
    catch SocketException sockE )
    {
      // can deal?
    }
    
    return null;
  }
  
  // get the address a server sees when you make a request
  // 'whatismyip.org' style resolution
  private static InetAddress getReflectedAddress()
  {
    // RLR TODO - this will be a standard homerun service
    // but need to encypt or obfuscate to prevent abuse
    return null;
  }
  
  public static void main(String[] args)
  {
    System.out.println"OS: " + System.getProperty"os.name" +
                    " vsn: " + System.getProperty"os.version" +
                    " on: " + System.getProperty"os.arch" ) );
    InetAddress local =  getLocalAddress();
    if local != null )
    {
      System.out.println"localAddress: " + local.getHostAddress() );
    }
    else
    {
      System.out.println"localAddress not found" );
    }
  }
}

   
    
    
    
  
Related examples in the same category
1.Programmatic Access to Network Parameters
2.An updated version of the ListNets program that uses the NetworkInterface enhancements
3.Get MAC address of a host: java.net.NetworkInterface.getHardwareAddress().
4.Report By Name
5.List Network Interfaces
6.Extract network card address with java.net.NetworkInterface
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.