像在百度搜索引擎输入IP就能获取到本人的本机IP,如何用java实现?

2025-03-18 05:25:44
推荐回答(1个)
回答1:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package baidu;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 *
 * @author stcdasqy
 */
public class Baidu {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception{
       URL url = new URL("http://1111.ip138.com/ic.asp");
       URLConnection conn = url.openConnection();
       InputStream is = conn.getInputStream();
       byte buf[] = new byte[40];
       int len;
       String ret = "";
       while((len=is.read(buf))!=-1){
           ret += new String(buf,"GB2312");
       }
       is.close();
       String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";  
        Pattern p = Pattern.compile(regex);  
        Matcher m = p.matcher(ret); 
        
        if(m.find()){
            
              System.out.println(m.group(0));
        }
       
    }
    
    
}
这样就可以了