Java获取本机的内网IP和公网IP(通…

内网IP

try   {
   InetAddress[]   ia   =   InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
   for(int   i=0;i
   System.out.print(ia[i].getHostAddress().toString());
  }
  }   catch   (UnknownHostException   ex)   {
   //   TODO   自动生成   catch   块
   ex.printStackTrace();
  }

 

公网IP


  try {
   URL url = new URL("http://www.ip138.com/ip2city.asp");
     URLConnection conn = url.openConnection();
     conn.setRequestProperty(
      "User-Agent",
      "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15");
     conn.setRequestProperty("Content-Type", "text/html");
     conn.setRequestProperty("Accept",
      "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
     InputStream is = conn.getInputStream();
     BufferedReader br = new BufferedReader(new InputStreamReader(is,
       "GB2312"));
     String line = null;
     while ((line = br.readLine()) != null) {
      if (line.contains("您的IP地址是")) {
       // System.out.println(line);
       int start = line.indexOf('[') + 1;
       int end = line.indexOf(']');
       System.out.println(line.substring(start, end));
      }
     }
     br.close();
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }

 

 

你可能感兴趣的:(java)