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






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();
      while( ifaces.hasMoreElements() )
      {
        NetworkInterface netIf = (NetworkInterface)ifaces.nextElement();
        Enumeration addrs = netIf.getInetAddresses();
        while( addrs.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