你可以用这个方法读取你所需要的本机IP地址
=======================================================
J2SE50新特性之ProcessBuilder
这个例子使用了J2SE50的ProcessBuilder类执行外部的程序,相对于 Runtimeexec ,它更方便,可以设置环境变量等。这里使用它在windows下读取物理网卡的地址
package comkuaffjdk5package;
import javaioIOException;
import javaioInputStream;
import javautilArrayList;
import javautilList;
public class ProcessBuilderShow
{
public static List getPhysicalAddress()
{
Process p = null;
//物理网卡列表
List address = new ArrayList();
try
{
//执行ipconfig /all命令
p = new ProcessBuilder("ipconfig", "/all")start();
}
catch (IOException e)
{
return address;
}
byte[] b = new byte[1024];
StringBuffer sb = new StringBuffer();
//读取进程输出值
InputStream in = pgetInputStream();
try
{
while (inread(b)>0)
{
sbappend(new String(b));
}
}
catch (IOException e1)
{
}
finally
{
try
{
inclose();
}
catch (IOException e2)
{
}
}
//以下分析输出值,得到物理网卡
String rtValue = sbsubstring(0);
int i = rtValueindexOf("Physical Address :");
while(i>0)
{
rtValue = rtValuesubstring(i + "Physical Address :"length());
addressadd(rtValuesubstring(0,18));
i = rtValueindexOf("Physical Address :");
}
return address;
}
public static void main(String[] args)
{
List address = ProcessBuilderShowgetPhysicalAddress();
for(String add:address)
{
Systemoutprintf("物理网卡地址:%s%n", add);
}
}
}import javanetInetAddress;
import javanetUnknownHostException;
public class Test
{
public static void main(String[] args) throws UnknownHostException
{
InetAddress inet = InetAddressgetLocalHost();
Systemoutprintln("本机的ip=" + inetgetHostAddress());
}
}java获取本机的外网ip示例:
import javaioIOException;
import javaioInputStream;
import javanet>
public static void main(String[] args) {
try {
Systemoutprintln("当前时间:"+new Date());
Systemoutprintln("IP地址 : " + InetAddressgetLocalHost());
} catch (UnknownHostException e) {
eprintStackTrace();
}
}
import javanet;public class Test6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
InetAddress ia=null;
try {
ia=iagetLocalHost();
String localname=iagetHostName();
String localip=iagetHostAddress();
Systemoutprintln("本机名称是:"+ localname);
Systemoutprintln("本机的ip是 :"+localip);
} catch (Exception e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)