Created
April 18, 2013 06:29
-
-
Save ninozhang/5410610 to your computer and use it in GitHub Desktop.
Java 获取本地 IP 地址
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.InetAddress; | |
import java.net.NetworkInterface; | |
import java.net.SocketException; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
import java.util.Enumeration; | |
import org.apache.log4j.Logger; | |
public abstract class IPUtil { | |
private static Logger logger = Logger.getLogger(IPUtil.class); | |
public static Collection<InetAddress> getAllHostAddress() { | |
try { | |
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface | |
.getNetworkInterfaces(); | |
Collection<InetAddress> addresses = new ArrayList<InetAddress>(); | |
while (networkInterfaces.hasMoreElements()) { | |
NetworkInterface networkInterface = networkInterfaces | |
.nextElement(); | |
Enumeration<InetAddress> inetAddresses = networkInterface | |
.getInetAddresses(); | |
while (inetAddresses.hasMoreElements()) { | |
InetAddress inetAddress = inetAddresses.nextElement(); | |
addresses.add(inetAddress); | |
logger.info("Host Address:" + inetAddress.getHostAddress() | |
+ " @ " + inetAddress.getHostName()); | |
} | |
} | |
return addresses; | |
} catch (SocketException e) { | |
throw new RuntimeException(e.getMessage(), e); | |
} | |
} | |
public static Collection<String> getAllNoLoopbackAddresses() { | |
Collection<String> noLoopbackAddresses = new ArrayList<String>(); | |
Collection<InetAddress> allInetAddresses = getAllHostAddress(); | |
for (InetAddress address : allInetAddresses) { | |
if (!address.isLoopbackAddress()) { | |
noLoopbackAddresses.add(address.getHostAddress()); | |
} | |
} | |
return noLoopbackAddresses; | |
} | |
public static String getFirstNoLoopbackAddress() { | |
Collection<String> allNoLoopbackAddresses = getAllNoLoopbackAddresses(); | |
return allNoLoopbackAddresses.iterator().next(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment