JAVA 获取本地所有的IP地址,多网卡多IP,单网卡多个IP

对于JAVA获取本机IP的代码很多,感觉都是相互转载的,所以我看到的都是能够正确获得多个网卡的多个IP,对于一块网卡绑定多个IP的。


首先感谢那些无私的代码奉献者,让我少动了几下爪机。


废话少说,上代码

public static ArrayList getLocalIP(String startWiths)
{
ArrayList iplist = new ArrayList();
boolean loop=true;
String bindip=null;
Enumeration network;
List netlist=new ArrayList();
try {
network = NetworkInterface.getNetworkInterfaces();

while (network.hasMoreElements()) {
loop=true;
NetworkInterface ni=(NetworkInterface)network.nextElement();

if(ni.isLoopback() || ni.getName().startsWith("eth")==false){
continue;
}
netlist.add(0,ni);

InetAddress ip=null;
//System.out.println(ni.getDisplayName() + " " + ni.getName());
for(NetworkInterface list:netlist){
if(loop==false) break;
Enumeration card = list.getInetAddresses();
while(card.hasMoreElements()){
while(true){
ip = null;
try{
ip = (InetAddress) card.nextElement();
}catch(Exception e){

}
if(ip==null){
break;
}
if(!ip.isLoopbackAddress()){
if(ip.getHostAddress().equalsIgnoreCase("127.0.0.1")){
continue;
}
}
if(ip instanceof Inet6Address) {
continue;
}
if(ip instanceof Inet4Address) {
bindip=ip.getHostAddress();

if(bindip.startsWith(startWiths)){
boolean addto=true;
for(int n=0; n if( bindip.equals((String)iplist.get(n)) ){
addto=false;
break;
}
}
if(addto){
iplist.add(bindip);
}
}else{
//System.out.println(bindip + " is out");
}
break;
}
}
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
netlist=null;
/*System.out.println("==============");
for(int n=0; n System.out.println(n + ": " + iplist.get(n));
}
System.out.println("==============");
*/
return iplist;
}




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;


你可能感兴趣的:(JAVA 获取本地所有的IP地址,多网卡多IP,单网卡多个IP)