자바 공공 네트워크 (외부 네트워크 IP) 획득 실 용적!

1737 단어
package com.lovo.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class PublicInterIp {
	/**
	 * @param args
	 * @throws Exception
	 */
	public String getPublicIp() {
		try {
			String path = "http://iframe.ip138.com/ic.asp";//    html       

			URL url = new URL(path);//   url  

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();//     

			conn.setRequestProperty("contentType", "GBK"); //   url      

			conn.setConnectTimeout(5 * 1000);//      

			conn.setRequestMethod("GET");//     

			InputStream inStream = conn.getInputStream();
			// readLesoSysXML(inStream);

			BufferedReader in = new BufferedReader(new InputStreamReader(
					inStream, "GBK"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			//             ,  
			while ((line = in.readLine()) != null) {
				buffer.append(line);
			}
			String str = buffer.toString();
			String ipString1 = str.substring(str.indexOf("[")); 
			//     IP    [182.149.82.50]  
			String ipsString2 = ipString1.substring(ipString1.indexOf("[") + 1,
					ipString1.lastIndexOf("]"));
			//    IP      
		/*	String ipsString3=ipString1.substring(ipString1.indexOf(": "),ipString1.lastIndexOf(""));
			System.err.println(ipsString3);*/
			
			//     IP 
			return ipsString2;

		} catch (Exception e) {
			System.out.println("    IP    ");
			return "    ";
		}
	}
	public static void main(String[] args)  { 
		PublicInterIp interIp=new PublicInterIp();
		System.err.println(interIp.getPublicIp());
	}
}

좋은 웹페이지 즐겨찾기