package com.sunny.system.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class LANAddress {
String WIN7_KEY = "IPv4 地址 . . . . . . . . . . . . :";
/**
* 有可能有多个IP[有时代理上网时,可以设置多个IP]
* @return
*/
public List<String> getLocalAddress(){
List<String> ips = null;
Runtime rt = Runtime.getRuntime();
try {
//需要区别是什么操作系统 ,此处略.....
//例如linux下好像是 ifconfig ?
Process proc = rt.exec("ipconfig");
InputStream in = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(in,"GBK");
BufferedReader br = new BufferedReader(isr);
String line = null;
while((line = br.readLine()) != null){
int index = 0;
if((index = line.indexOf(WIN7_KEY))!=-1){
if(ips==null)
ips = new ArrayList<String>();
//String ip = line.substring(index + WIN7_KEY.length());
//System.out.println("localhost : " + ip);
ips.add(line.substring(index + WIN7_KEY.length()).trim());
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ips;
}
public static void main(String[] args) {
List<String> ips = new LANAddress().getLocalAddress();
if(ips!=null)
for(String ip:ips){
System.out.println("localhost : " + ip);
}
}
}
|