您的位置:首页 > 移动开发 > Android开发

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

2016-06-13 21:12 741 查看
最近做一个文件传输的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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: