android如何获得本机地址(包括开启热点的手机)

最近做一个文件传输的APP,需要调用本机的IP地址,在网上找了一些参考资料:

第一种方法:参考  http://blog.csdn.net/cazicaquw/article/details/7571725 

private String getlocalip(){
		WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);  
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();  
		int ipAddress = wifiInfo.getIpAddress(); 
		Log.d(Tag, "int ip "+ipAddress);
		if(ipAddress==0)return null;
		return ((ipAddress & 0xff)+"."+(ipAddress>>8 & 0xff)+"."
				+(ipAddress>>16 & 0xff)+"."+(ipAddress>>24 & 0xff));
	}

但是这种方法对于开启热点的手机不适用。

其中用到把 adress IP地址 和 数字进行转换:

参考:http://www.blogjava.net/javagrass/archive/2011/07/08/353921.html

http://android.blog.51cto.com/268543/392896/

方法参考http://www.sharejs.com/codes/java/5529

/**
 * @author SunChong
 */
public class IpUtil {
	
	/**
	 * 将字符串型ip转成int型ip
	 * @param strIp
	 * @return
	 */
	public static int Ip2Int(String strIp){
		String[] ss = strIp.split("\\.");
		if(ss.length != 4){
			return 0;
		}
		byte[] bytes = new byte[ss.length];
		for(int i = 0; i < bytes.length; i++){
			bytes[i] = (byte) Integer.parseInt(ss[i]);
		}
		return byte2Int(bytes);
	}
	/**
	 * 将int型ip转成String型ip
	 * @param intIp
	 * @return
	 */
	public static String int2Ip(int intIp){
		byte[] bytes = int2byte(intIp);
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < 4; i++){
			sb.append(bytes[i] & 0xFF);
			if(i < 3){
				sb.append(".");
			}
		}
		return sb.toString();
	}
	
	private static byte[] int2byte(int i) {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) (0xff & i);
        bytes[1] = (byte) ((0xff00 & i) >> 8);
        bytes[2] = (byte) ((0xff0000 & i) >> 16);
        bytes[3] = (byte) ((0xff000000 & i) >> 24);
        return bytes;
    }
	private static int byte2Int(byte[] bytes) {
        int n = bytes[0] & 0xFF;
        n |= ((bytes[1] << 8) & 0xFF00);
        n |= ((bytes[2] << 16) & 0xFF0000);
        n |= ((bytes[3] << 24) & 0xFF000000);
        return n;
    }
	
	public static void main(String[] args) {
		String ip1 = "192.168.0.1";
		int intIp = Ip2Int(ip1);
		String ip2 = int2Ip(intIp);
		System.out.println(ip2.equals(ip1));
	}
}

//该代码片段来自于: http://www.sharejs.com/codes/java/5529

第二种方法:

用UDP广播地址,向全频道255.255.255.255广播,但是开启热点的手机也不能向255.255.255.255广播,发不出去,不过连接上该热点的手机可以发送。

想用开启热点广播也可以,从1-255挨个挨个发,如何得到当前IP段,如手机的192.168.43.xxx 可以参考http://www.2cto.com/kf/201510/448077.html

这样对方能收到你的IP ,并按照这个IP发回来,这样能同时得到自己的IP 和对方的IP


第三种方法:

这是最简单方便的。

/*2016.6.11
	 * 得到本机IP地址
	 * */
	public String getLocalIpAddress(){
		try{
			Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); 
			while(en.hasMoreElements()){
				NetworkInterface nif = en.nextElement();
				Enumeration<InetAddress> enumIpAddr = nif.getInetAddresses();
				while(enumIpAddr.hasMoreElements()){
					InetAddress mInetAddress = enumIpAddr.nextElement();
					if(!mInetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(mInetAddress.getHostAddress())){
						return mInetAddress.getHostAddress().toString();
					}
				}
			}
		}catch(SocketException ex){
			Log.e("MyFeiGeActivity", "获取本地IP地址失败");
		}
		
		return null;
	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 在Android手机中,要获取手机的IP地址,我们可以使用Java网络编程中的InetAddress类。InetAddress类提供了许多静态方法,例如getByName()和getLocalHost()来获取IP地址。 下面是获取手机IP地址的步骤: 1. 获取一个表示本地主机的InetAddress对象:InetAddress localHost = InetAddress.getLocalHost(); 2. 获取本地主机名:String hostName = localHost.getHostName(); 3. 根据主机名获取一个InetAddress数组:InetAddress[] addrs = InetAddress.getAllByName(hostName); 4. 遍历InetAddress数组,获取IP地址:String ipAddress = "";for (InetAddress addr : addrs) { if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress() && addr instanceof Inet4Address) { ipAddress = addr.getHostAddress(); break; }} 5. 最后获得的就是本机的IP地址。 获取IP地址的过程可能会抛出异常,比如网络不可用或者域名解析失败等。我们需要在程序中进行相应的异常处理,以确保程序能够正常运行。 总体来说,我们可以通过Java的InetAddress类来获取Android手机的IP地址。这样,我们就能使用这个地址来建立网络连接,实现与其他设备的交互。 ### 回答2: Android系统作为一款常用的移动操作系统,具有广泛的用户基础。在使用移动设备时,获取IP地址非常重要,因为它可以帮助用户识别自己的设备,并能够将信息准确地发送到哪台设备上。下面将详细介绍如何在Android设备上获取IP地址。 1. 通过WIFI获取IP地址Android设备上,通过WIFI获取IP地址是最常用的方法,具体步骤如下: 1) 点击设置按钮打开Android系统设置界面,在该界面中,找到“WLAN”选项并点击进入。 2) 打开Wi-Fi选项卡,寻找对应的WIFI热点并连接。 3) 在连接成功后,点击已连接的WIFI名称,可以看到WIFI详细信息,其中包括了当前设备的IP地址。 2. 通过移动数据获取IP地址 除了WIFI以外,移动数据同样可以获取Android设备的IP地址。但需要说明的是,移动数据获取的IP地址通常是动态的,随时会发生变化,而WIFI获取的IP地址通常是静态的,不会随时变化。 要获取Android设备的移动数据IP地址,可以通过以下步骤实现: 1) 点击设置按钮打开Android系统设置界面,在该界面中,找到“SIM卡和移动网络”选项并点击进入。 2) 点击移动网络选项卡,找到“高级选项”或“APN”选项卡。 3) 点击“APN”选项卡,找到当前使用的移动网络提供商的APN设置。 4) 在APN设置中,可以找到“IP地址”项,该项为当前设备的IP地址。 需要注意的是,如果您在使用4G网络时,您的IP地址可能会由于网络变更而发生变化。而在3G网络上,IP地址一般是不会发生变化的。 综上所述,获取Android手机的IP地址是一个比较简单的操作,用户可以通过上述方式轻松实现,而这些信息可以帮助用户更好地了解自己的设备。 ### 回答3: 在Android平台上,获取设备的IP地址可以按照以下步骤进行: 1.获取设备的网络连接管理器(NetworkInfo)对象,并检查网络连接类型,以获得正确的IP地址。 ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { int type = networkInfo.getType(); if (type == ConnectivityManager.TYPE_WIFI || type == ConnectivityManager.TYPE_ETHERNET) { //get wifi or Ethernet IP address } else if (type == ConnectivityManager.TYPE_MOBILE) { //get mobile IP address } } 2.如果连接类型为Wi-Fi或以太网,则可以通过NetworkInterface类获取设备的IP地址。 try { Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces(); while (networks.hasMoreElements()) { NetworkInterface network = networks.nextElement(); if (network.getName().equalsIgnoreCase("wlan0") || network.getName().equalsIgnoreCase("eth0")) { Enumeration<InetAddress> addresses = network.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (!address.isLinkLocalAddress() && !address.isLoopbackAddress() && address instanceof Inet4Address) { String ipAddress = address.getHostAddress(); //return wifi or Ethernet IP address } } } } } catch (SocketException e) { //handle exception } 3.如果连接类型为移动网络,则可以通过TelephonyManager类获取本机手机号码,再通过http请求获取移动网络的公网IP地址。 TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String phoneNumber = telephonyManager.getLine1Number(); if (phoneNumber != null && !phoneNumber.isEmpty()) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { String publicIp = ""; try { URL url = new URL("http://checkip.dyndns.org"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String response = reader.readLine(); int index = response.indexOf(": "); int endIndex = response.indexOf("</body>"); publicIp = response.substring(index + 2, endIndex); } catch (IOException e) { e.printStackTrace(); } return publicIp; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); //return mobile IP address } }.execute(); } 通过以上步骤,我们就可以获取到Android设备的IP地址了。同时,需要注意的是,为了避免读取到Link-local地址和Loopback地址,我们需要在获取IP地址的过程中进行判断和过滤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

obession

觉得有用可以打赏咖啡一杯~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值