Android 获取本地外网IP、内网IP、计算机名等信息

来源:互联网 发布:c语言菜单设计模板 编辑:程序博客网 时间:2024/05/22 15:14

、获取本地外网IP
 

[java] view plaincopyprint?
  1. public static String GetNetIp()  
  2.     {  
  3.         URL infoUrl = null;  
  4.         InputStream inStream = null;  
  5.         try  
  6.         {  
  7.             //http://iframe.ip138.com/ic.asp  
  8.             //infoUrl = new URL("http://city.ip138.com/city0.asp");  
  9.             infoUrl = new URL("http://iframe.ip138.com/ic.asp");  
  10.             URLConnection connection = infoUrl.openConnection();  
  11.             HttpURLConnection httpConnection = (HttpURLConnection)connection;  
  12.             int responseCode = httpConnection.getResponseCode();  
  13.             if(responseCode == HttpURLConnection.HTTP_OK)  
  14.             {   
  15.                 inStream = httpConnection.getInputStream();   
  16.                 BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"utf-8"));  
  17.                 StringBuilder strber = new StringBuilder();  
  18.                 String line = null;  
  19.                 while ((line = reader.readLine()) != null)   
  20.                     strber.append(line + "\n");  
  21.                 inStream.close();  
  22.                 //从反馈的结果中提取出IP地址  
  23.                 int start = strber.indexOf("[");  
  24.                 int end = strber.indexOf("]", start + 1);  
  25.                 line = strber.substring(start + 1, end);  
  26.                 return line;   
  27.             }  
  28.         }  
  29.         catch(MalformedURLException e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.         catch (IOException e) {  
  33.             e.printStackTrace();  
  34.         }  
  35.         return null;  
  36.     }  

 


二、 获取本地内网IP

 

[java] view plaincopyprint?
  1. // 获取本地IP函数  
  2.         public static String getLocalIPAddress() {  
  3.             try {  
  4.                 for (Enumeration<NetworkInterface> mEnumeration = NetworkInterface  
  5.                         .getNetworkInterfaces(); mEnumeration.hasMoreElements();) {  
  6.                     NetworkInterface intf = mEnumeration.nextElement();  
  7.                     for (Enumeration<InetAddress> enumIPAddr = intf  
  8.                             .getInetAddresses(); enumIPAddr.hasMoreElements();) {  
  9.                         InetAddress inetAddress = enumIPAddr.nextElement();  
  10.                         // 如果不是回环地址  
  11.                         if (!inetAddress.isLoopbackAddress()) {  
  12.                             // 直接返回本地IP地址  
  13.                             return inetAddress.getHostAddress().toString();  
  14.                         }  
  15.                     }  
  16.                 }  
  17.             } catch (SocketException ex) {  
  18.                 System.err.print("error");  
  19.             }  
  20.             return null;  
  21.         }  


 三、 获取本地外网IP、内网IP、计算机名等信息

[java] view plaincopyprint?
  1. /** 
  2.  *功能: 获取外网IP,内网IP,计算机名等信息; 
  3.  *  
  4.  *作者: jef 
  5.  *  
  6.  *时间: 20100714 
  7.  *  
  8.  *版本: v1.0.0 
  9.  *  
  10.  *  
  11.  *程序说明: 
  12.  *      通过纯真网络来获取IP,因为ip138网站有时不准。 
  13.  *   
  14.  *      运行程序时命令行参数请输入http://www.cz88.net/ip/viewip778.aspx 
  15.  *      等待程序运行完毕(执行时间视网络情况而定),会在程序目录下生成一个GETIP.sys文件来输出各参数。 
  16.  *   
  17.  *      运行时如果不输入命令行参数,则默认使用http://www.cz88.net/ip/viewip778.aspx来获取IP。 
  18.  *   
  19.  *      注意, 
  20.  *      不输入命令行参数时获取的信息会输出到命令行,不会输出到文件。 
  21.  *      输入命令行参数时获取的信息则会输出到文件,不管获取IP成功与否。 
  22.  *   
  23.  *      输出信息部分内容的含义如下, 
  24.  *      sucess 
  25.  *      hostName is:MyPC 
  26.  *      hostAddr is:192.168.1.114 
  27.  *      Foreign IP is:210.72.100.9 
  28.  *      Location is:江苏省苏州 长城宽带 
  29.  *      ...... 
  30.  *   
  31.  *      第一行表示全部过程成功与否。成功输出"sucess",否则"fail", 
  32.  *      第二行表示计算机名, 
  33.  *      第三行表示内网IP, 
  34.  *      第四行表示外网IP, 
  35.  *      第五行表示外网IP所有的可能地理位置(可信度依赖于查询的网站)。 
  36.  *      ...... 
  37.  *   
  38.  *   
  39.  *使用举例: 
  40.  *      拷贝 \cn\mail\sendback\GetIP.class 文件到C:\Documents and Settings下。注意要保留包名的目录。 
  41.  *      打开命令提示行窗口,输入: 
  42.  *    
  43.  *      c: 
  44.  *      cd C:\Documents and Settings 
  45.  *      java cn.mail.sendback.GetIP http://www.cz88.net/ip/viewip778.aspx 
  46.  *    
  47.  *      等待C:\Documents and Settings目录下出现GETIP.sys文件则表示执行完毕, 
  48.  *      用记事本打开该文件。含义见说明部分。 
  49.  *    
  50.  */  
  51.   
  52.   
  53. package com.soai.test;  
  54.   
  55. import java.io.BufferedReader;  
  56. import java.io.BufferedWriter;  
  57. import java.io.FileNotFoundException;  
  58. import java.io.FileOutputStream;  
  59. import java.io.IOException;  
  60. import java.io.InputStreamReader;  
  61. import java.io.OutputStream;  
  62. import java.io.OutputStreamWriter;  
  63. import java.net.InetAddress;  
  64. import java.net.URL;  
  65. import java.net.UnknownHostException;  
  66. import java.util.Date;  
  67.   
  68. public class GetIP {  
  69.   
  70.     /** 
  71.      * @param args 
  72.      */  
  73.     public static void main(String[] args){  
  74.         // 通过纯真网络来获取IP,因为ip138网站有时不准。  
  75.         // 运行程序时命令行输入:http://www.cz88.net/ip/viewip778.aspx  
  76.   
  77.         boolean bHasNoArgs =false;  
  78.         if(args.length<=0) bHasNoArgs =true;  
  79.   
  80.         StringBuffer sbFileContent =new StringBuffer();  
  81.         boolean bGetSuccess =true;  
  82.           
  83.         try {  
  84.             InetAddress host =InetAddress.getLocalHost();  
  85.               
  86.             String hostName =host.getHostName();  
  87.             String hostAddr=host.getHostAddress();  
  88.             String tCanonicalHostName =host.getCanonicalHostName();  
  89.   
  90.             Date da =new Date();  
  91.             String osname =System.getProperty("os.name");  
  92.             String osversion =System.getProperty("os.version");  
  93.             String username =System.getProperty("user.name");  
  94.             String userhome =System.getProperty("user.home");  
  95.             String userdir =System.getProperty("user.dir");  
  96.               
  97.             if(bHasNoArgs){  
  98.                 System.out.println("hostName is:"+hostName);  
  99.                 System.out.println("hostAddr is:"+hostAddr);  
  100.   
  101.                 System.out.println("Current Date is:"+da.toString());  
  102.                 System.out.println("osname is:"+osname);  
  103.                 System.out.println("osversion is:"+osversion);  
  104.                 System.out.println("username is:"+username);  
  105.                 System.out.println("userhome is:"+userhome);  
  106.                 System.out.println("userdir is:"+userdir);  
  107.             }  
  108.             else{  
  109.                 sbFileContent.append("hostName is:"+hostName+"\n");  
  110.                 sbFileContent.append("hostAddr is:"+hostAddr+"\n");  
  111.                   
  112.                 sbFileContent.append("Current Date is:"+da.toString()+"\n");  
  113.                 sbFileContent.append("osname is:"+osname+"\n");  
  114.                 sbFileContent.append("osversion is:"+osversion+"\n");  
  115.                 sbFileContent.append("username is:"+username+"\n");  
  116.                 sbFileContent.append("userhome is:"+userhome+"\n");  
  117.                 sbFileContent.append("userdir is:"+userdir+"\n");  
  118.             }  
  119.               
  120.             StringBuffer url =new StringBuffer();  
  121.             if(bHasNoArgs||args[0].equals(null)||args[0].equals("")){  
  122.                 url.append("http://www.cz88.net/ip/viewip778.aspx");  
  123.             }  
  124.             else  
  125.                 url.append(args[0]);  
  126.             StringBuffer strForeignIP =new StringBuffer("strForeignIPUnkown");  
  127.             StringBuffer strLocation =new StringBuffer("strLocationUnkown");  
  128.               
  129.               
  130.             if(GetIP.getWebIp(url.toString(),strForeignIP,strLocation)){  
  131.                 if(bHasNoArgs){  
  132.                     System.out.println("Foreign IP is:"+strForeignIP);  
  133.                     System.out.println("Location is:"+strLocation);  
  134.                 }  
  135.                 else{  
  136.                     sbFileContent.append("Foreign IP is:"+strForeignIP+"\n");  
  137.                     sbFileContent.append("Location is:"+strLocation+"\n");  
  138.                 }  
  139.             }  
  140.             else{  
  141.                 if(bHasNoArgs){  
  142.                     System.out.println("Failed to connect:"+url);  
  143.                 }  
  144.                 else{  
  145.                     bGetSuccess =false;  
  146.                     sbFileContent.append("Failed to connect:"+url+"\n");  
  147.                 }  
  148.             }  
  149.               
  150.               
  151.         } catch (UnknownHostException e) {  
  152.             if(bHasNoArgs){  
  153.                 e.printStackTrace();  
  154.             }  
  155.             else{  
  156.                 bGetSuccess =false;  
  157.                 sbFileContent.append(e.getStackTrace()+"\n");  
  158.             }  
  159.         }  
  160.           
  161.           
  162.         if(bGetSuccess)  
  163.             sbFileContent.insert(0,"sucess"+"\n");  
  164.         else  
  165.             sbFileContent.insert(0,"fail"+"\n");  
  166.               
  167.         if(!bHasNoArgs) write2file(sbFileContent);  
  168.           
  169.     }  
  170.   
  171.       
  172.      public static boolean getWebIp(String strUrl,  
  173.              StringBuffer strForeignIP,StringBuffer strLocation) {  
  174.           try {  
  175.   
  176.            URL url = new URL(strUrl);  
  177.   
  178.            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));  
  179.   
  180.            String s = "";  
  181.            StringBuffer sb = new StringBuffer("");  
  182.            while ((s = br.readLine()) != null) {  
  183.             sb.append(s + "\r\n");  
  184.            }  
  185.            br.close();  
  186.              
  187.            String webContent = "";  
  188.            webContent = sb.toString();  
  189.              
  190.            if( webContent.equals(null)|| webContent.equals("") ) return false;  
  191.             
  192.              
  193.              
  194.            String flagofForeignIPString ="IPMessage";  
  195.            int startIP = webContent.indexOf(flagofForeignIPString)+flagofForeignIPString.length()+2;  
  196.            int endIP = webContent.indexOf("</span>",startIP);  
  197.            strForeignIP.delete(0, webContent.length());  
  198.            strForeignIP.append(webContent.substring(startIP,endIP));  
  199.   
  200.            String flagofLocationString ="AddrMessage";  
  201.            int startLoc = webContent.indexOf(flagofLocationString)+flagofLocationString.length()+2;  
  202.            int endLoc = webContent.indexOf("</span>",startLoc);  
  203.            strLocation.delete(0, webContent.length());  
  204.            strLocation.append(webContent.substring(startLoc,endLoc));            
  205.              
  206.            return true;  
  207.   
  208.           } catch (Exception e) {  
  209.            //e.printStackTrace();  
  210.            return false;  
  211.           }  
  212.          }    
  213.        
  214.   
  215.      public static void  write2file(StringBuffer content){  
  216.   
  217.          if(content.length()<=0return;  
  218.            
  219.             try {  
  220.                 FileOutputStream fos = new FileOutputStream("GETIP.sys");  
  221.                 OutputStreamWriter osr =new OutputStreamWriter(fos);  
  222.                 BufferedWriter bw =new BufferedWriter(osr);   
  223.                   
  224.                 try {  
  225.                     int index =0;  
  226.                     while(index>=0){  
  227.                         int preIndex =index;  
  228.                         index =content.indexOf("\n", preIndex+2);  
  229.                           
  230.                         if(index>0){  
  231.                             String str =new String(content.substring(preIndex, index));  
  232.                             bw.write(str);  
  233.                             bw.newLine();  
  234.                         }  
  235.                         else{  
  236.                             String str =new String(content.substring(preIndex, content.length()-1));  
  237.                             bw.write(str);  
  238.                             break;  
  239.                         }  
  240.                     }  
  241.                       
  242.                 } catch (IOException e1) {  
  243.                     // TODO Auto-generated catch block  
  244.                     //e1.printStackTrace();  
  245.                 }  
  246.                   
  247.                 try {  
  248.                     bw.close();  
  249.                 } catch (IOException e) {  
  250.                     // TODO Auto-generated catch block  
  251.                     //e.printStackTrace();  
  252.                 }  
  253.             } catch (FileNotFoundException e) {  
  254.                 // TODO Auto-generated catch block  
  255.                 //e.printStackTrace();  
  256.             }  
  257.      }  
  258. }  
0 0
原创粉丝点击