我需要檢查我的Android應用是否存在到主機的路由。這裏是我的代碼:RequestRouteToHost不起作用
private void ensureRouteToHost(String proxyAddr) throws IOException
{
ConnectivityManager connMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
int inetAddr;
inetAddr = lookupHost(proxyAddr); // Return -938825536 for IP 192.168.10.200
Log.d(TAG, "host for proxy is " + inetAddr);
if (inetAddr == -1)
{
Log.e(TAG, "cannot establish route for " + proxyAddr + ": unkown host");
throw new IOException("Cannot establish route for " + proxyAddr + ": Unknown host");
}
else
{
int[] apnTypes = new int[] {ConnectivityManager.TYPE_MOBILE, ConnectivityManager.TYPE_MOBILE_MMS, ConnectivityManager.TYPE_MOBILE_DUN, ConnectivityManager.TYPE_MOBILE_HIPRI, ConnectivityManager.TYPE_MOBILE_SUPL};
for (int i=0; i<apnTypes.length; i++)
{
if (connMgr.requestRouteToHost(apnTypes[i], inetAddr))
{
Log.d(TAG, "route to host requested");
return;
}
}
Log.e(TAG, "unable to request route to host");
throw new IOException("Cannot establish route to proxy " + inetAddr);
}
}
public static int lookupHost(String hostname)
{
hostname = hostname.substring(0, hostname.indexOf(":") > 0 ? hostname.indexOf(":") : hostname.length());
String result = "";
String[] array = hostname.split("\\.");
if (array.length != 4) return -1;
int[] hexArray = new int[] {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
hexArray[0] = Integer.parseInt(array[0])/16;
hexArray[1] = Integer.parseInt(array[0]) % 16;
hexArray[2] = Integer.parseInt(array[1])/16;
hexArray[3] = Integer.parseInt(array[1]) % 16;
hexArray[4] = Integer.parseInt(array[2])/16;
hexArray[5] = Integer.parseInt(array[2]) % 16;
hexArray[6] = Integer.parseInt(array[3])/16;
hexArray[7] = Integer.parseInt(array[3]) % 16;
for (int i=0; i<8; i++)
{
result += Integer.toHexString(hexArray[i]);
}
return Long.valueOf(Long.parseLong(result, 16)).intValue();
}
它完美對大多數設備,但,這是很奇怪,它不會在Nexus S的歐洲工作。我試了幾次Nexus,我總是遇到這個問題。 當我撥打connMgr.requestRouteToHost(apnTypes[i], inetAddr)
時,問題位於ensureRouteToHost
方法中。無論我輸入什麼,它總是返回假。我的計劃是檢查IP 192.168.10.200
是否可用於我的MMS應用程序。 這不適用於公共IP,如stackoverflow.com(作爲整數69.59.197.21或1161544981)。
那麼,你有一個想法,爲什麼這不適用於某些設備? 感謝您閱讀我的話題。
您的代碼在Galaxy Nexus GSM(CyanogenMod 10)上運行,並帶有TYPE_MOBILE(顯然只有在啓用移動數據連接時) – bwt
感謝您的反饋。它適用於Xperia T 4.0.3,Desire S 4.0.4,Galaxy S3 4.1,Huawei Ascend P1 4.0.3等等。這些問題出現在Nexus S歐洲版本4.0.3下。數據在所有設備上啓用。更換SIM卡並不能解決問題。 – Manitoba