用java得到本机所有的ip地址

2008-02-23 09:17:17来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

package com.sourceware.util;

import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.HttpClient;
import org.apache.log4j.Logger;
import Java.net.InetAddress;
import java.util.Enumeration;
import java.net.NetworkInterface;
import java.util.*;

/**
*
* <p>Title: Sourceware utils.</p>
*
* <p>Description: Sourceware utils.</p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: Sourceware inc.</p>
*
* @author 黑山(woowind@sina.com)
* @version 1.0
*/
public class NetUtil {

static Logger logger = Logger.getLogger(NetUtil.class);

public NetUtil() {
}

/**
*
* @param url String
* @return int
* @throws Exception
*/
public static int clickURL(String url) throws Exception {
int retrycount = 3;
while (true) {
HttpClient httpClient = new HttpClient();
GetMethod get = new GetMethod(url);
get.addRequestHeader("Content-Type", "text/html; charset=GBK");
int code = httpClient.executeMethod(get);
if (code != 200) {
if (retrycount == 0) {
throw new Exception("发送失败,失败原因=" code);
}
logger.error("send to[" url "]error code[" code "]");
retrycount--;
}
else {
return code;
}

} //end while(true)...
}

/**
*
* @return Collection
*/
public static Collection getAllLocalIP() throws Exception {
ArrayList ar = new ArrayList();
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
InetAddress ip = (InetAddress) ni.getInetAddresses().nextElement();
if (!ip.isSiteLocalAddress() && !ip.isLooPBackAddress() &&
ip.getHostAddress().indexOf(":") == -1) {
System.out.println("Interface " ni.getName()
" seems to be InternetInterface. I'll take it..."); ;
}
else {
ar.add(ip.getHostAddress());
}
}
return ar;
}

public static void main(String[] args) {
try {
NetUtil.getAllLocalIP();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}

上一篇: Reading Design Patterns
下一篇: 使用tomcat4.1.31和mysql 配置数据源

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:anti trick Ⅰ -- OpenProcess

下一篇:选取合适的dHtml Grid方案