java 取所以ip方法

 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.*;


 public class TestGetMacAddr {

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

   public TestGetMacAddr() {
   }

   /**
    *
    * @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 {
      Collection col = TestGetMacAddr.getAllLocalIP();
      Iterator it = col.iterator();
      while (it.hasNext()){
       System.out.println(it.next());
      }
     }
     catch (Exception ex) {
       ex.printStackTrace();
     }
   }
 }

你可能感兴趣的:(java,apache,html,log4j,.net)