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

2 篇文章 0 订阅

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();
    }
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值