80,356
社区成员
发帖
与我相关
我的任务
分享
public String getIpAddress(){
String ipAddress = "";
try{
ipAddress = wifiIpAddress();
if(ipAddress!=null&&ipAddress.trim().length()>0){
}else{
ipAddress = this.GPRSIpAddress();
}
}catch(Exception ex){
}
return ipAddress;//有IP返回就联网
}
private String wifiIpAddress(){
String ip = "";
//获取wifi服务
WifiManager wifiManager = (WifiManager)(context).getSystemService(Context.WIFI_SERVICE);
//判断wifi是否开启
if (wifiManager.isWifiEnabled()) {
//wifiManager.setWifiEnabled(true);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
ip = intToIp(ipAddress);
}
return ip;
}
private String intToIp(int i) {
return (i & 0xFF ) + "." +
((i >> 8 ) & 0xFF) + "." +
((i >> 16 ) & 0xFF) + "." +
( i >> 24 & 0xFF) ;
}
private String GPRSIpAddress(){
try{
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()){
return inetAddress.getHostAddress().toString();
}
}
}
}catch (SocketException ex){
Log.d("GPRSIpAddress IpAddress", ex.toString());
}
return "";
}