此方法来源于网络,简单修改后,测试通过,返回地址格式为“192.168.1.109”
public String getlocalIp() throws SocketException
{String ipaddress = null;
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf = en.nextElement();
if (intf.getName().toLowerCase().equals("eth0")
|| intf.getName().toLowerCase().equals("wlan0"))
{
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress())
{
ipaddress = inetAddress.getHostAddress().toString();
if (!ipaddress.contains("::"))
{// ipV6的地址
return ipaddress;
}
}
}
} else
{
continue;
}
}
return ipaddress;
}