获取IP地址以可读形式的Android code [英] Getting IP address in a readable form android code
本文介绍了获取IP地址以可读形式的Android code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新android开发,我做它发送一个Android设备的IP地址,另外一个通过手机短信的应用程序。我需要得到知识产权的十进制这样192.168.0.4不是,我从下面的code有十六进制。任何想法如何做到这一点,感谢您的帮助。
公共字符串getLocalIpAddress()
{
尝试 {
对于(枚举<的NetworkInterface> EN = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements()){
NetworkInterface的INTF = en.nextElement();
对于(枚举< InetAddress类> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements()){
InetAddress类InetAddress类= enumIpAddr.nextElement();
如果(!inetAddress.isLoopbackAddress()){
返回inetAddress.getHostAddress()的toString()。
}
}
}
}赶上(SocketException前){
Log.e(TAG,ex.toString());
}
返回null;
}
解决方案
公共静态字符串getLocalIpv4Address(){
尝试 {
字符串的IPv4;
名单<的NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
如果(nilist.size()大于0){
对于(的NetworkInterface妮:nilist){
名单< InetAddress类> ialist = Collections.list(ni.getInetAddresses());
如果(ialist.size()大于0){
对于(InetAddress类地址:ialist){
如果(address.isLoopbackAddress()及!&安培; InetAddressUtils.isIPv4Address(IPv4的= address.getHostAddress())){
返回IPv4的;
}
}
}
}
}
}赶上(SocketException前){
}
返回 ;
}
如果这行吗?这个函数将返回的IPv4(以xxx.xxx.xxx.xxx模式),只有可用。
请注意,您提到的十六进制值应该是一个IPv6地址。
I am new to android development and I am doing an application which sends the IP address of an android device to another one by sms. I need to get the IP in decimal like this 192.168.0.4 not in hexadecimal which I got from the below code. any idea how to do that and thanks for the help.
public String getLocalIpAddress()
{
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.e(TAG, ex.toString());
}
return null;
}
解决方案
public static String getLocalIpv4Address(){
try {
String ipv4;
List<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
if(nilist.size() > 0){
for (NetworkInterface ni: nilist){
List<InetAddress> ialist = Collections.list(ni.getInetAddresses());
if(ialist.size()>0){
for (InetAddress address: ialist){
if (!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4=address.getHostAddress())){
return ipv4;
}
}
}
}
}
} catch (SocketException ex) {
}
return "";
}
Should this be ok ? This function will return ipv4 (in xxx.xxx.xxx.xxx pattern) only if available.
Please note that those hexadecimal value you mentioned should be an ipv6 address.
这篇关于获取IP地址以可读形式的Android code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文