我的应用程序采用组播发送周期的信标以及协议消息和主机加入组播组的IP。在Android设备它返回127.0.0.1。我环顾四周,发现有不少人建议更改主机文件。但是,万一机器人的,不可能在我的上下文。我如何获得设备的真实IP,而不是回送地址。
私人无效getLocalAddress()
{
尝试 {
字符串本地主机= InetAddress.getLocalHost()getHostAddress()。
servers.add(本地);
}赶上(UnknownHostException异常E){
e.printStackTrace();
}
}
解决方案
修改几个位而这一次是工作根据需要获取IPv4地址。 !inetAddress.isLoopbackAddress()删除所有的环回地址。 !inetAddress.isLinkLocalAddress()和inetAddress.isSiteLocalAddress())将删除所有IPv6地址。我希望这将有助于有人在这里。
StringBuilder的IFCONFIG =新的StringBuilder();
尝试 {
对于(枚举<的NetworkInterface> EN = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements()){
NetworkInterface的INTF = en.nextElement();
对于(枚举< InetAddress类> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements()){
InetAddress类InetAddress类= enumIpAddr.nextElement();
如果(inetAddress.isLoopbackAddress()及!&安培;!inetAddress.isLinkLocalAddress()&安培;&安培; inetAddress.isSiteLocalAddress()){
IFCONFIG.append(inetAddress.getHostAddress()的toString()+\ N);
}
}
}
}赶上(SocketException前){
Log.e(LOG_TAG,ex.toString());
}
servers.add(IFCONFIG.toString());
My application uses multicast to send a beacon in periods along with protocol message and ip of the host joining the multicast group. In android device it is returning 127.0.0.1. I have looked around and found that many people suggested changing a host file. But, in case of android it is not possible in my context. How do I get real IP of the device, not the loopback address..
private void getLocalAddress()
{
try {
String localHost = InetAddress.getLocalHost().getHostAddress();
servers.add(localHost);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
解决方案
Modified few bits and this one is working as desired for getting IPv4 addresses. !inetAddress.isLoopbackAddress() removes all the loopback address. !inetAddress.isLinkLocalAddress() and inetAddress.isSiteLocalAddress()) removes all IPv6 addresses. I hope this will help someone in here.
StringBuilder IFCONFIG=new StringBuilder();
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() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
IFCONFIG.append(inetAddress.getHostAddress().toString()+"\n");
}
}
}
} catch (SocketException ex) {
Log.e("LOG_TAG", ex.toString());
}
servers.add(IFCONFIG.toString());
上一篇:作为枚举类属性类属