一、獲取本地外網IP
public static String GetNetIp()
{
URL infoUrl = null;
InputStream inStream = null;
try
{
//http://iframe.ip138.com/ic.asp
//infoUrl = new URL("http://city.ip138.com/city0.asp");
infoUrl = new URL("http://iframe.ip138.com/ic.asp");
URLConnection connection = infoUrl.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
inStream = httpConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
//從反饋的結果中提取出IP地址
int start = strber.indexOf("[");
int end = strber.indexOf("]", start + 1);
line = strber.substring(start + 1, end);
return line;
}
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
二、 獲取本地內網IP
// 獲取本地IP函數
public static String getLocalIPAddress() {
try {
for (Enumeration<NetworkInterface> mEnumeration = NetworkInterface
.getNetworkInterfaces(); mEnumeration.hasMoreElements();) {
NetworkInterface intf = mEnumeration.nextElement();
for (Enumeration<InetAddress> enumIPAddr = intf
.getInetAddresses(); enumIPAddr.hasMoreElements();) {
InetAddress inetAddress = enumIPAddr.nextElement();
// 如果不是迴環地址
if (!inetAddress.isLoopbackAddress()) {
// 直接返回本地IP地址
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
System.err.print("error");
}
return null;
}
三、 獲取本地外網IP、內網IP、計算機名等信息
/**
*功能: 獲取外網IP,內網IP,計算機名等信息;
*
*作者: jef
*
*時間: 20100714
*
*版本: v1.0.0
*
*
*程序說明:
* 通過純真網絡來獲取IP,因爲ip138網站有時不準。
*
* 運行程序時命令行參數請輸入http://www.cz88.net/ip/viewip778.aspx
* 等待程序運行完畢(執行時間視網絡情況而定),會在程序目錄下生成一個GETIP.sys文件來輸出各參數。
*
* 運行時如果不輸入命令行參數,則默認使用http://www.cz88.net/ip/viewip778.aspx來獲取IP。
*
* 注意,
* 不輸入命令行參數時獲取的信息會輸出到命令行,不會輸出到文件。
* 輸入命令行參數時獲取的信息則會輸出到文件,不管獲取IP成功與否。
*
* 輸出信息部分內容的含義如下,
* sucess
* hostName is:MyPC
* hostAddr is:192.168.1.114
* Foreign IP is:210.72.100.9
* Location is:江蘇省蘇州 長城寬帶
* ......
*
* 第一行表示全部過程成功與否。成功輸出"sucess",否則"fail",
* 第二行表示計算機名,
* 第三行表示內網IP,
* 第四行表示外網IP,
* 第五行表示外網IP所有的可能地理位置(可信度依賴於查詢的網站)。
* ......
*
*
*使用舉例:
* 拷貝 \cn\mail\sendback\GetIP.class 文件到C:\Documents and Settings下。注意要保留包名的目錄。
* 打開命令提示行窗口,輸入:
*
* c:
* cd C:\Documents and Settings
* java cn.mail.sendback.GetIP http://www.cz88.net/ip/viewip778.aspx
*
* 等待C:\Documents and Settings目錄下出現GETIP.sys文件則表示執行完畢,
* 用記事本打開該文件。含義見說明部分。
*
*/
package com.soai.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Date;
public class GetIP {
/**
* @param args
*/
public static void main(String[] args){
// 通過純真網絡來獲取IP,因爲ip138網站有時不準。
// 運行程序時命令行輸入:http://www.cz88.net/ip/viewip778.aspx
boolean bHasNoArgs =false;
if(args.length<=0) bHasNoArgs =true;
StringBuffer sbFileContent =new StringBuffer();
boolean bGetSuccess =true;
try {
InetAddress host =InetAddress.getLocalHost();
String hostName =host.getHostName();
String hostAddr=host.getHostAddress();
String tCanonicalHostName =host.getCanonicalHostName();
Date da =new Date();
String osname =System.getProperty("os.name");
String osversion =System.getProperty("os.version");
String username =System.getProperty("user.name");
String userhome =System.getProperty("user.home");
String userdir =System.getProperty("user.dir");
if(bHasNoArgs){
System.out.println("hostName is:"+hostName);
System.out.println("hostAddr is:"+hostAddr);
System.out.println("Current Date is:"+da.toString());
System.out.println("osname is:"+osname);
System.out.println("osversion is:"+osversion);
System.out.println("username is:"+username);
System.out.println("userhome is:"+userhome);
System.out.println("userdir is:"+userdir);
}
else{
sbFileContent.append("hostName is:"+hostName+"\n");
sbFileContent.append("hostAddr is:"+hostAddr+"\n");
sbFileContent.append("Current Date is:"+da.toString()+"\n");
sbFileContent.append("osname is:"+osname+"\n");
sbFileContent.append("osversion is:"+osversion+"\n");
sbFileContent.append("username is:"+username+"\n");
sbFileContent.append("userhome is:"+userhome+"\n");
sbFileContent.append("userdir is:"+userdir+"\n");
}
StringBuffer url =new StringBuffer();
if(bHasNoArgs||args[0].equals(null)||args[0].equals("")){
url.append("http://www.cz88.net/ip/viewip778.aspx");
}
else
url.append(args[0]);
StringBuffer strForeignIP =new StringBuffer("strForeignIPUnkown");
StringBuffer strLocation =new StringBuffer("strLocationUnkown");
if(GetIP.getWebIp(url.toString(),strForeignIP,strLocation)){
if(bHasNoArgs){
System.out.println("Foreign IP is:"+strForeignIP);
System.out.println("Location is:"+strLocation);
}
else{
sbFileContent.append("Foreign IP is:"+strForeignIP+"\n");
sbFileContent.append("Location is:"+strLocation+"\n");
}
}
else{
if(bHasNoArgs){
System.out.println("Failed to connect:"+url);
}
else{
bGetSuccess =false;
sbFileContent.append("Failed to connect:"+url+"\n");
}
}
} catch (UnknownHostException e) {
if(bHasNoArgs){
e.printStackTrace();
}
else{
bGetSuccess =false;
sbFileContent.append(e.getStackTrace()+"\n");
}
}
if(bGetSuccess)
sbFileContent.insert(0,"sucess"+"\n");
else
sbFileContent.insert(0,"fail"+"\n");
if(!bHasNoArgs) write2file(sbFileContent);
}
public static boolean getWebIp(String strUrl,
StringBuffer strForeignIP,StringBuffer strLocation) {
try {
URL url = new URL(strUrl);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String s = "";
StringBuffer sb = new StringBuffer("");
while ((s = br.readLine()) != null) {
sb.append(s + "\r\n");
}
br.close();
String webContent = "";
webContent = sb.toString();
if( webContent.equals(null)|| webContent.equals("") ) return false;
String flagofForeignIPString ="IPMessage";
int startIP = webContent.indexOf(flagofForeignIPString)+flagofForeignIPString.length()+2;
int endIP = webContent.indexOf("</span>",startIP);
strForeignIP.delete(0, webContent.length());
strForeignIP.append(webContent.substring(startIP,endIP));
String flagofLocationString ="AddrMessage";
int startLoc = webContent.indexOf(flagofLocationString)+flagofLocationString.length()+2;
int endLoc = webContent.indexOf("</span>",startLoc);
strLocation.delete(0, webContent.length());
strLocation.append(webContent.substring(startLoc,endLoc));
return true;
} catch (Exception e) {
//e.printStackTrace();
return false;
}
}
public static void write2file(StringBuffer content){
if(content.length()<=0) return;
try {
FileOutputStream fos = new FileOutputStream("GETIP.sys");
OutputStreamWriter osr =new OutputStreamWriter(fos);
BufferedWriter bw =new BufferedWriter(osr);
try {
int index =0;
while(index>=0){
int preIndex =index;
index =content.indexOf("\n", preIndex+2);
if(index>0){
String str =new String(content.substring(preIndex, index));
bw.write(str);
bw.newLine();
}
else{
String str =new String(content.substring(preIndex, content.length()-1));
bw.write(str);
break;
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
//e1.printStackTrace();
}
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
}