利用正则表达式获取网卡的MAC地址 获取IP地址

import java.io.*;
import java.util.regex.*;
import java.net.*;
import java.util.*;
public class ReadMacByJava
{
private String mPhysicalAddress = “”;
private int mPhysicalMacNumber = 0;
private boolean isInit = false;

public ReadMacByJava()
{
}

public void init()
{
try
{
String line;
Process process = Runtime.getRuntime().exec(“cmd /c ipconfig /all”);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
Pattern macPattern =                      Pattern.compile(“([0-9A-Fa-f]{2})(-[0

-9A-Fa-f]{2}){5}”);
Matcher macMatcher;
boolean result;
while ((line = bufferedReader.readLine()) != null)
{
if (“”.equals(line))
continue;
macMatcher = macPattern.matcher(line);
result = macMatcher.find();
if (result)
{
mPhysicalMacNumber++;
if (“”.equals(mPhysicalAddress))
mPhysicalAddress = macMatcher.group(0);
else
mPhysicalAddress += (“,” + macMatcher.group(0));
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
isInit = true;
}
public String getPhysicalAddress()
{
if (isInit)
return this.mPhysicalAddress;
else
return “Mac is not init.”;
}
public int getPhysicalMacNumber()
{
if (isInit)
return this.mPhysicalMacNumber;
else
{
System.out.println(“Mac is not init.”);
return 0;
}
}
public static String getIp(){
String localip=null;//本地IP,如果没有配置外网IP则返回它
String netip=null;//外网IP
try {
Enumeration<NetworkInterface> netInterfaces =
NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
boolean finded=false;//是否找到外网IP
while(netInterfaces.hasMoreElements() && !finded){
NetworkInterface ni=netInterfaces.nextElement();
Enumeration<InetAddress> address=ni.getInetAddresses();
while(address.hasMoreElements()){
ip=address.nextElement();
System.out.println(ni.getName() +”;”+ip.getHostAddress()

+”;ip.isSiteLocalAddress()=”+ip.isSiteLocalAddress()+”;ip.isLoopbackAddress()

=”+ip.isLoopbackAddress());
if( !ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(“:”)==-1){//外网IP
netip=ip.getHostAddress();
finded=true;
break;
}else if(ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(“:”)==-1){//内网IP
localip=ip.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
if(netip!=null && !”".equals(netip)){
return netip;
}else{
return localip;
}
}

public static void main(String[] args)
{
ReadMacByJava mac = new ReadMacByJava();
mac.init();
System.out.println(“MAC “+mac.getPhysicalMacNumber()+” address :”          +

mac.getPhysicalAddress());
System.out.println(“ip address= “+getIp());
}
}

MAC 1 address :00-E0-4C-00-9F-AB
lo;127.0.0.1;ip.isSiteLocalAddress()=false;ip.isLoopbackAddress()=true
eth0;192.168.1.4;ip.isSiteLocalAddress()=true;ip.isLoopbackAddress()=false
ip address= 192.168.1.4

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>