MyException - 我的异常网
当前位置:我的异常网» Java Web开发 » 在java中,如果分别获取本地的两块网卡的IP地址解决

在java中,如果分别获取本地的两块网卡的IP地址解决思路

www.MyException.Cn  网友分享于:2015-08-27  浏览:37次
在java中,如果分别获取本地的两块网卡的IP地址
一台服务器有两块网卡,A为内网用,配置有192.168网段IP地址,网卡B为公网IP,现在我想获取B的ip地址,而不是A的,应该如何处理啊?

------解决方案--------------------
信 誉 值: 95 怎么搞的?

获取系统版本+本地IP地址+网卡物理地址-java
获取系统版本+本地IP地址+网卡物理地址-java

//NetworkInfo.java



import java.net.InetAddress;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.StringTokenizer;
public final class NetworkInfo
{
public final static String getMacAddress() throws IOException
{
String os = System.getProperty( "os.name ");
try
{
if (os.startsWith( "Windows "))
{
return windowsParseMacAddress(windowsRunIpConfigCommand());

}

else if (os.startsWith( "Linux "))

{
return linuxParseMacAddress(linuxRunIfConfigCommand());
}
else
{
throw new IOException( "unknown operating system: " + os);
}
}
catch (ParseException ex)
{
ex.printStackTrace();
throw new IOException(ex.getMessage());
}
}
/* * Linux stuff */

private final static String linuxParseMacAddress(String ipConfigResponse) throws
ParseException
{
String localHost = null;
try
{
localHost = InetAddress.getLocalHost().getHostAddress();
}
catch (java.net.UnknownHostException ex)
{
ex.printStackTrace();
throw new ParseException(ex.getMessage(), 0);
}
StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n ");
String lastMacAddress = null;
while (tokenizer.hasMoreTokens())
{
String line = tokenizer.nextToken().trim();
boolean containsLocalHost = line.indexOf(localHost) > = 0; // see if line contains IP address
if (containsLocalHost && lastMacAddress != null)
{
return lastMacAddress;
} // see if line contains MAC address
int macAddressPosition = line.indexOf( "HWaddr ");
if (macAddressPosition <= 0)
continue;
String macAddressCandidate = line.substring(macAddressPosition + 6).
trim();
if (linuxIsMacAddress(macAddressCandidate))
{
lastMacAddress = macAddressCandidate;
continue;
}
}
ParseException ex = new ParseException( "cannot read MAC address for " +
localHost + " from [ " +
ipConfigResponse + "] ", 0);
ex.printStackTrace();
throw ex;
}

private final static boolean linuxIsMacAddress(String macAddressCandidate)
{ // TODO: use a smart regular expression
if (macAddressCandidate.length() != 17)
return false;
return true;
}

private final static String linuxRunIfConfigCommand() throws IOException
{
Process p = Runtime.getRuntime().exec( "ifconfig ");
InputStream stdoutStream = new BufferedInputStream(p.getInputStream());

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有