1、Java获取本地IP地址方法网上搜一箩筐,但基本上都是获得一个IP,实际开发中一台电脑很可能有多个IP地址,如多网卡,或者安装了VM Ware虚拟机,就会虚拟出其他的网卡,那么传统的方法得到的一个IP地址就不全面了,下面贴出获取本机IP列表的方法:
/**
* IceWee 2013.07.19
* 获取本地IP列表(针对多网卡情况)
*
* @return
*/
public
static List<String> getLocalIPList()
{
List<String> ipList = new ArrayList<String>();
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
NetworkInterface networkInterface;
Enumeration<InetAddress> inetAddresses;
InetAddress inetAddress;
String ip;
while (networkInterfaces.hasMoreElements()) {
networkInterface = networkInterfaces.nextElement();
inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
inetAddress = inetAddresses.nextElement();
if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
ip = inetAddress.getHostAddress();
ipList.add(ip);
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return ipList;
}
2、获取多网卡时的本机IP
1. public String getLocalHostName() {
2. String hostName;
3. try {
4. InetAddress addr = InetAddress.getLocalHost();
5. hostName = addr.getHostName();
6. catch (Exception ex) {
7. "";
8. }
9. return hostName;
10. }
11.
12. public String[] getAllLocalHostIP() {
13. null;
14. try {
15. String hostName = getLocalHostName();
16. if (hostName.length() > 0) {
17. InetAddress[] addrs = InetAddress.getAllByName(hostName);
18. if (addrs.length > 0) {
19. new String[addrs.length];
20. for (int i = 0; i < addrs.length; i++) {
21. ret[i] = addrs[i].getHostAddress();
22. }
23. }
24. }
25.
26. catch (Exception ex) {
27. null;
28. }
29. return ret;
30. }
31.