linux環境で実際のipアドレスを取得
6972 ワード
package inas.test;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* IP
* @author lyh
* @version 2012-7-5
* @see IpGetter
* @since
*/
public class IpGetter
{
/**
*
*/
private static final String NETWORK_CARD = "eth0";
/**
*
*/
private static final String NETWORK_CARD_BAND = "bond0";
/**
*
* Description: <br>
* @return
* @see
*/
public static String getLocalHostName()
{
try
{
InetAddress addr = InetAddress.getLocalHost();
return addr.getHostName();
}
catch (Exception e)
{
System.out.println("IpGetter.getLocalHostName ! :" + e.getMessage());
return "";
}
}
/**
* Description: linux IPv4 IP<br>
* @return
* @see
*/
public static String getLocalIP()
{
String ip = "";
try
{
Enumeration<NetworkInterface> e1 = (Enumeration<NetworkInterface>)NetworkInterface.getNetworkInterfaces();
while (e1.hasMoreElements())
{
NetworkInterface ni = e1.nextElement();
//
if ((NETWORK_CARD.equals(ni.getName()))
|| (NETWORK_CARD_BAND.equals(ni.getName())))
{
Enumeration<InetAddress> e2 = ni.getInetAddresses();
while (e2.hasMoreElements())
{
InetAddress ia = e2.nextElement();
if (ia instanceof Inet6Address)
{
continue;
}
ip = ia.getHostAddress();
}
break;
}
else
{
continue;
}
}
}
catch (SocketException e)
{
System.out.println("IpGetter.getLocalIP ! :" + e.getMessage());
}
return ip;
}
public static void main(String[] args) {
IpGetter ipGetter =new IpGetter();
String str = IpGetter.getLocalIP();
System.out.println("ip :"+str);
}
}