public String GetIpAddress() {
Enumeration<NetworkInterface> netInterfaces = null;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
System.out.println("DisplayName:" + ni.getDisplayName());
System.out.println("Name:" + ni.getName());
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
InetAddress ip = ips.nextElement();
if (!ip.isLoopbackAddress()) {
return ip.getHostAddress();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
在android系统的pad中是不需要区分是网线连接和无论是通过apache方式连接如:
HttpClient httpClient = new DefaultHttpClient(); // 自动获取网络
if(NetworkHelpers.queryPreferedNetworkType(context) != ConnectivityManager.TYPE_WIFI) {
APN apn = NetworkHelpers.queryPreferedApn(context);
String proxyStr = apn.getProxy();
if(!TextUtils.isEmpty(proxyStr) && !TextUtils.isEmpty(apn.getPort()) && apn.getPort().matches("[0-9]*")) {
HttpHost proxy = new HttpHost(apn.getProxy(),
Integer.parseInt(apn.getPort()));
httpClient.getParams().setParameter(
ConnRoutePNames.DEFAULT_PROXY, proxy);
}
}
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIME_OUT);
try {
HttpUriRequest request = null;
if (postValues == null) {
HttpGet getter = new HttpGet(urlStr);
request = getter;
} else {
HttpPost poster = new HttpPost(urlStr);
poster.setEntity(new UrlEncodedFormEntity(postValues, ENCODE_UTF_8));
request = poster;
}
HttpResponse response = httpClient.execute(request);
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
in = entity.getContent();
}
android 方式连接如:
URL url = new URL(info.mUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(TIME_OUT);
都能自动区分网络类型通过测试应该会优先选择无线网络,如果没有无线网络会选择有线