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

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

www.MyException.Cn  网友分享于:2015-08-27  浏览:37次

StringBuffer buffer = new StringBuffer();
for (; ; )
{
int c = stdoutStream.read();
if (c == -1)
break;
buffer.append( (char) c);
}
String outputText = buffer.toString();
stdoutStream.close();
return outputText;
}
/* * Windows stuff */

private final static String windowsParseMacAddress(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(); // see if line contains IP address
if (line.endsWith(localHost) && lastMacAddress != null)
{
return lastMacAddress;
} // see if line contains MAC address
int macAddressPosition = line.indexOf( ": ");
if (macAddressPosition <= 0)
continue;
String macAddressCandidate = line.substring(macAddressPosition + 1).
trim();
if (windowsIsMacAddress(macAddressCandidate))//&Egrave;&iexcl;&micro;&Atilde;MAC&micro;&Oslash;&Ouml;·
{
lastMacAddress = macAddressCandidate;
continue;
}
}
ParseException ex = new ParseException( "cannot read MAC address from [ " +
ipConfigResponse + "] ", 0);
ex.printStackTrace();
throw ex;
}

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

private final static String windowsRunIpConfigCommand() throws IOException
{
Process p = Runtime.getRuntime().exec( "ipconfig /all ");
InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer = new StringBuffer();
for (; ; )
{
int c = stdoutStream.read();
if (c == -1)
break;
buffer.append( (char) c);
}
String outputText = buffer.toString();
stdoutStream.close();
return outputText;
}
/* * Main */

public final static void main(String[] args)
{
try
{
System.out.println( "Network infos: ");
System.out.println( " Operating System: " +System.getProperty( "os.name "));
System.out.println( " IP/Localhost: " +InetAddress.getLocalHost().getHostAddress());
System.out.println( " MAC Address: " + getMacAddress());
}
catch (Throwable t)
{
t.printStackTrace();
}
}
}


------解决方案--------------------
难道只有调用系统的命令行才能得到IP信息!??????有没有其他方法泥!?

文章评论

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