我是新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.
上一篇:如何自定义ToolStripTextBox的渲染?自定义、ToolStripTextBox
下一篇:配置项目或摇篮:解决依赖于摇篮当创建新项目的Android工作室坚持':类路径:“摇篮、路径、新项目、工作室