Skip to content

Instantly share code, notes, and snippets.

@zacscoding
Created March 22, 2018 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zacscoding/232a1671f24fe49b8178d3580e8f235e to your computer and use it in GitHub Desktop.
Save zacscoding/232a1671f24fe49b8178d3580e8f235e to your computer and use it in GitHub Desktop.
ip utils..
package util;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* @author zacconding
* @Date 2018-01-14
* @GitHub : https://github.com/zacscoding
*/
public class IpUtil {
/**
* Get ip address from network interfaces
*
* @return ip addr or null
*/
public static String getIpAddr() {
try {
Enumeration<NetworkInterface> networkEnum = NetworkInterface.getNetworkInterfaces();
while (networkEnum.hasMoreElements()) {
NetworkInterface ni = networkEnum.nextElement();
if (ni.isLoopback()) {
continue;
}
Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress ia = inetAddresses.nextElement();
if (ia.getHostAddress() != null && ia.getHostAddress().indexOf(".") != -1) {
return ia.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment