获取本机IP\MAC
正好要做一个读取本机IP和MAC地址的练习,发现windows下和linux的不一样,于是干脆一起来做工厂模式练习~不过返回都是String - -。
首先是IPReader接口和MACReader接口,表示可以读取IP和MAC的行为:
-
package net.reader;
-
-
public interface IPReader {
-
-
-
}
-
-
package net.reader;
-
-
public interface MACReader {
-
-
-
}
Windows下的实现类
-
package net.reader;
-
-
import java.net.InetAddress;
-
import java.net.UnknownHostException;
-
-
-
public class WindowsIPReader implements IPReader {
-
-
String ip;
-
try {
-
ip = "Can not read ip!";
-
e.printStackTrace();
-
}
-
return ip;
-
}
-
-
}
-
package net.reader;
-
-
import java.io.*;
-
-
-
public class WindowsMACReader implements MACReader {
-
-
String mac = null;
-
try {
-
String s, str = "";
-
while((s=br.readLine())!=null){
-
if(s.contains("Physical Address")){
-
mac = s.substring(44);
-
break;
-
}
-
}
-
mac = "Cannot read MAC Address!";
-
e.printStackTrace();
-
}
-
return mac;
-
}
-
-
}
Linux下的实现类
-
package net.reader;
-
-
import java.io.BufferedReader;
-
import java.io.IOException;
-
import java.io.InputStreamReader;
-
-
public class LinuxIPReader implements IPReader {
-
-
String ip = null;
-
try {
-
String s, str = "";
-
while((s=br.readLine())!=null){
-
if(s.contains("inet addr")){
-
ip = s.substring(20,35);
-
break;
-
}
-
}
-
ip = "Cannot read IP Address!";
-
e.printStackTrace();
-
}
-
return ip;
-
}
-
-
}
然后是抽象工厂
Windows实现类
Linux实现类
最后是一个创建工厂的工厂 = =
输出部分:
-
package net;
-
-
import net.factory.*;
-
-
public class NetProgramTest {
-
-
try{
-
NetFactory factory = SystemFactory.getInstance();
-
}
-
}
-
-
}
在winXP和redhat9.0下测试可行~