下面列出了java.net.NetworkInterface#getNetworkInterfaces ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void configureSuperUserIPAddresses(Configuration conf,
String superUserShortName) throws IOException {
ArrayList<String> ipList = new ArrayList<String>();
Enumeration<NetworkInterface> netInterfaceList = NetworkInterface
.getNetworkInterfaces();
while (netInterfaceList.hasMoreElements()) {
NetworkInterface inf = netInterfaceList.nextElement();
Enumeration<InetAddress> addrList = inf.getInetAddresses();
while (addrList.hasMoreElements()) {
InetAddress addr = addrList.nextElement();
ipList.add(addr.getHostAddress());
}
}
StringBuilder builder = new StringBuilder();
for (String ip : ipList) {
builder.append(ip);
builder.append(',');
}
builder.append("127.0.1.1,");
builder.append(InetAddress.getLocalHost().getCanonicalHostName());
LOG.info("Local Ip addresses: " + builder.toString());
conf.setStrings(DefaultImpersonationProvider.getTestProvider().
getProxySuperuserIpConfKey(superUserShortName),
builder.toString());
}
public static void main(String[] args) throws Exception {
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
while (nics.hasMoreElements()) {
NetworkInterface nic = nics.nextElement();
for (InterfaceAddress iaddr : nic.getInterfaceAddresses()) {
boolean valid = checkPrefix(iaddr);
if (!valid) {
passed = false;
debug(nic.getName(), iaddr);
}
InetAddress ia = iaddr.getAddress();
if (ia.isLoopbackAddress() && ia instanceof Inet4Address) {
// assumption: prefix length will always be 8
if (iaddr.getNetworkPrefixLength() != 8) {
out.println("Expected prefix of 8, got " + iaddr);
passed = false;
}
}
}
}
if (!passed)
throw new RuntimeException("Failed: some interfaces have invalid prefix lengths");
}
public static InetAddress getWiFiIpAddress() {
try {
for (Enumeration<NetworkInterface> enNetI = NetworkInterface
.getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
NetworkInterface netI = enNetI.nextElement();
if (netI.getDisplayName().equals("wlan0") || netI.getDisplayName().equals("eth0")) {
for (Enumeration<InetAddress> enumIpAddr = netI
.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
return inetAddress;
}
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
private String getAddress() {
try {
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
InetAddress ip = ips.nextElement();
if (ip.getHostAddress().equals("127.0.0.1")) {
continue;
}
if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
return ip.getHostAddress();
}
}
}
} catch (Exception e) {
log.error("get ip failed", e);
}
return null;
}
/**
* Returns a list of all the addresses on the system.
* @param inclLoopback
* if {@code true}, include the loopback addresses
* @param ipv4Only
* it {@code true}, only IPv4 addresses will be included
*/
static List<InetAddress> getAddresses(boolean inclLoopback,
boolean ipv4Only)
throws SocketException {
ArrayList<InetAddress> list = new ArrayList<InetAddress>();
Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netInf : Collections.list(nets)) {
Enumeration<InetAddress> addrs = netInf.getInetAddresses();
for (InetAddress addr : Collections.list(addrs)) {
if (!list.contains(addr) &&
(inclLoopback ? true : !addr.isLoopbackAddress()) &&
(ipv4Only ? (addr instanceof Inet4Address) : true)) {
list.add(addr);
}
}
}
return list;
}
/**
* 获得外网IP
*
* @return 外网IP
*/
public static String getInternetIp() {
try {
Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
Enumeration<InetAddress> addrs;
while (networks.hasMoreElements()) {
addrs = networks.nextElement().getInetAddresses();
while (addrs.hasMoreElements()) {
ip = addrs.nextElement();
if (ip != null && ip instanceof Inet4Address && ip.isSiteLocalAddress()
&& !ip.getHostAddress().equals(INTRANET_IP)) {
return ip.getHostAddress();
}
}
}
// 如果没有外网IP,就返回内网IP
return INTRANET_IP;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void testAllNetworkInterfaces() throws Exception {
System.err.println("\n testAllNetworkInterfaces: \n ");
for (Enumeration<NetworkInterface> e = NetworkInterface
.getNetworkInterfaces(); e.hasMoreElements();) {
NetworkInterface netIF = e.nextElement();
for (Enumeration<InetAddress> iadrs = netIF.getInetAddresses(); iadrs
.hasMoreElements();) {
InetAddress iadr = iadrs.nextElement();
if (iadr instanceof Inet6Address) {
System.err.println("Test NetworkInterface: " + netIF);
Inet6Address i6adr = (Inet6Address) iadr;
System.err.println("Testing with " + iadr);
System.err.println(" scoped iface: "
+ i6adr.getScopedInterface());
testInet6AddressSerialization(i6adr, null);
}
}
}
}
/**
* Retrieve the first validated local ip address(the Public and LAN ip addresses are validated).
*
* @return the local address
* @throws SocketException the socket exception
*/
public static InetAddress getLocalInetAddress() throws SocketException {
// enumerates all network interfaces
Enumeration<NetworkInterface> enu = NetworkInterface.getNetworkInterfaces();
while (enu.hasMoreElements()) {
NetworkInterface ni = enu.nextElement();
if (ni.isLoopback()) {
continue;
}
Enumeration<InetAddress> addressEnumeration = ni.getInetAddresses();
while (addressEnumeration.hasMoreElements()) {
InetAddress address = addressEnumeration.nextElement();
// ignores all invalidated addresses
if (address.isLinkLocalAddress() || address.isLoopbackAddress() || address.isAnyLocalAddress()) {
continue;
}
return address;
}
}
throw new RuntimeException("No validated local address!");
}
/**
* Check if at least one network interface is up and active (i.e. has an address)
*
* @return true if network available
*/
static boolean checkNetwork() {
boolean up = false;
Enumeration<NetworkInterface> enumeration;
try {
enumeration = NetworkInterface.getNetworkInterfaces();
if (enumeration != null) {
while (!up && enumeration.hasMoreElements()) {
NetworkInterface networkInterface = enumeration.nextElement();
up = networkInterface.isUp() && !networkInterface.isLoopback()
&& networkInterface.getInetAddresses().hasMoreElements();
}
}
} catch (NoSuchMethodError error) {
ExchangeSession.LOGGER.debug("Unable to test network interfaces (not available under Java 1.5)");
up = true;
} catch (SocketException exc) {
ExchangeSession.LOGGER.error("DavMail configuration exception: \n Error listing network interfaces " + exc.getMessage(), exc);
}
return up;
}
/**
* Returns all local IP addresses (IPv4 and IPv6).
*
* @throws RuntimeException if resolution fails
*/
public static List<String> resolveLocalIPs(boolean ipv4Only) {
ArrayList<String> addresses = new ArrayList<>();
try {
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
while (nics.hasMoreElements()) {
NetworkInterface nic = nics.nextElement();
Enumeration<InetAddress> inetAddresses = nic.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress address = inetAddresses.nextElement();
if (address instanceof Inet6Address) {
if (!ipv4Only) {
addresses.add(toIpV6AddressName((Inet6Address) address));
}
} else {
addresses.add(address.getHostAddress());
}
}
}
} catch (SocketException e) {
throw new RuntimeException("Cannot resolve local network addresses", e);
}
return Collections.unmodifiableList(addresses);
}
/**
* 获取本机IP(2G/3G/4G)
*/
public static String getLocalIpBy3G() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&& inetAddress instanceof Inet4Address) {
// if (!inetAddress.isLoopbackAddress() && inetAddress
// instanceof Inet6Address) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Test
public void testConflictRegionServerHostnameConfigurationsAbortServer() throws Exception {
Enumeration<NetworkInterface> netInterfaceList = NetworkInterface.getNetworkInterfaces();
while (netInterfaceList.hasMoreElements()) {
NetworkInterface ni = netInterfaceList.nextElement();
Enumeration<InetAddress> addrList = ni.getInetAddresses();
// iterate through host addresses and use each as hostname
while (addrList.hasMoreElements()) {
InetAddress addr = addrList.nextElement();
if (addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isMulticastAddress()) {
continue;
}
String hostName = addr.getHostName();
LOG.info("Found " + hostName + " on " + ni);
TEST_UTIL.getConfiguration().set(DNS.MASTER_HOSTNAME_KEY, hostName);
// "hbase.regionserver.hostname" and "hbase.regionserver.hostname.disable.master.reversedns"
// are mutually exclusive. Exception should be thrown if both are used.
TEST_UTIL.getConfiguration().set(DNS.RS_HOSTNAME_KEY, hostName);
TEST_UTIL.getConfiguration().setBoolean(HRegionServer.RS_HOSTNAME_DISABLE_MASTER_REVERSEDNS_KEY, true);
try {
StartMiniClusterOption option = StartMiniClusterOption.builder()
.numMasters(NUM_MASTERS).numRegionServers(NUM_RS).numDataNodes(NUM_RS).build();
TEST_UTIL.startMiniCluster(option);
} catch (Exception e) {
Throwable t1 = e.getCause();
Throwable t2 = t1.getCause();
assertTrue(t1.getMessage()+" - "+t2.getMessage(), t2.getMessage().contains(
HRegionServer.RS_HOSTNAME_DISABLE_MASTER_REVERSEDNS_KEY + " and " +
DNS.RS_HOSTNAME_KEY + " are mutually exclusive"));
return;
} finally {
TEST_UTIL.shutdownMiniCluster();
}
assertTrue("Failed to validate against conflict hostname configurations", false);
}
}
}
public static String getIPAddress(Context context) {
Context appContext = context.getApplicationContext();
ConnectivityManager connectivityManager = (ConnectivityManager) appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return "";
}
@SuppressLint("MissingPermission") NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
try {
//Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
if (wifiManager == null) {
return "";
}
@SuppressLint("MissingPermission") WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = intIp2StrIp(wifiInfo.getIpAddress());//得到IPV4地址
return ipAddress;
}
}
else {
//当前无网络连接,请在设置中打开网络
}
return "";
}
/***
* 获取mac地址
* @return
*/
public static String getMacAddress() {
String address = null;
// 把当前机器上的访问网络接口的存入 Enumeration集合中
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface netWork = interfaces.nextElement();
// 如果存在硬件地址并可以使用给定的当前权限访问,则返回该硬件地址(通常是 MAC)。
byte[] by = netWork.getHardwareAddress();
if (by == null || by.length == 0) {
continue;
}
StringBuilder builder = new StringBuilder();
for (byte b : by) {
builder.append(String.format("%02X:", b));
}
if (builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
String mac = builder.toString();
// 从路由器上在线设备的MAC地址列表,可以印证设备Wifi的 name 是 wlan0
if (netWork.getName().equals("wlan0")) {
address = mac;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return address;
}
public static String getMacAddress() throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (!networkInterface.getName().equalsIgnoreCase("wlan0")) continue;
byte[] addresses = networkInterface.getHardwareAddress();
if (addresses == null || addresses.length == 0) return "";
StringBuilder builder = new StringBuilder();
for (byte b : addresses) {
builder.append(String.format(Locale.getDefault(), "%02x:", b));
}
return builder.deleteCharAt(builder.length() - 1).toString();
}
return "";
}
public static Set<String> getNetworkInterfaces(){
Set<String> ipAndHosts = new HashSet<>();
try {
// Get the system hostname and add it.
String hostName = getHostName();
ipAndHosts.add(hostName);
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
while (nics.hasMoreElements()) {
NetworkInterface nic = nics.nextElement();
ipAndHosts.add(nic.getDisplayName());
Enumeration<InetAddress> inets = nic.getInetAddresses();
while (inets.hasMoreElements()) {
InetAddress inet = inets.nextElement();
ipAndHosts.add(inet.getHostAddress());
ipAndHosts.add(inet.getHostName());
ipAndHosts.add(inet.getCanonicalHostName());
}
}
} catch (Exception e) {
logger.error(Constants.CONSOLE, "Error occurred acquiring IP's and hostnames", e);
}
return ipAndHosts;
}
public static String getLocalhostByNetworkInterface() throws SocketException {
List<String> candidatesHost = new ArrayList<String>();
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface networkInterface = enumeration.nextElement();
// Workaround for docker0 bridge
if ("docker0".equals(networkInterface.getName()) || !networkInterface.isUp()) {
continue;
}
Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress address = addrs.nextElement();
if (address.isLoopbackAddress()) {
continue;
}
//ip4 higher priority
if (address instanceof Inet6Address) {
candidatesHost.add(address.getHostAddress());
continue;
}
return address.getHostAddress();
}
}
if (!candidatesHost.isEmpty()) {
return candidatesHost.get(0);
}
return null;
}
/**
* Get IP address for localhost.
*
* @return IP address for localhost
*/
public static String getIp() {
if (null != cachedIpAddress) {
return cachedIpAddress;
}
Enumeration<NetworkInterface> netInterfaces;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (final SocketException ex) {
throw new HostException(ex);
}
String localIpAddress = null;
while (netInterfaces.hasMoreElements()) {
NetworkInterface netInterface = netInterfaces.nextElement();
Enumeration<InetAddress> ipAddresses = netInterface.getInetAddresses();
while (ipAddresses.hasMoreElements()) {
InetAddress ipAddress = ipAddresses.nextElement();
if (isPublicIpAddress(ipAddress)) {
String publicIpAddress = ipAddress.getHostAddress();
cachedIpAddress = publicIpAddress;
return publicIpAddress;
}
if (isLocalIpAddress(ipAddress)) {
localIpAddress = ipAddress.getHostAddress();
}
}
}
cachedIpAddress = localIpAddress;
return localIpAddress;
}
void setInterfaceNames() {
final String addressesRangeUSB = "192.168.42.";
final String addressesRangeWiFi = "192.168.43.";
usbTetherOn = false;
ethernetOn = false;
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
if (intf.isLoopback()) {
continue;
}
if (intf.isVirtual()) {
continue;
}
if (!intf.isUp()) {
continue;
}
setVpnInterfaceName(intf);
if (intf.isPointToPoint()) {
continue;
}
if (intf.getHardwareAddress() == null) {
continue;
}
if (intf.getName().replaceAll("\\d+", "").equalsIgnoreCase("eth")) {
ethernetOn = true;
ethernetInterfaceName = intf.getName();
Log.i(LOG_TAG, "LAN interface name " + ethernetInterfaceName);
}
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
String hostAddress = inetAddress.getHostAddress();
if (hostAddress.contains(addressesRangeWiFi)) {
this.apIsOn = true;
wifiAPInterfaceName = intf.getName();
Log.i(LOG_TAG, "WiFi AP interface name " + wifiAPInterfaceName);
}
if (hostAddress.contains(addressesRangeUSB)) {
usbTetherOn = true;
usbModemInterfaceName = intf.getName();
Log.i(LOG_TAG, "USB Modem interface name " + usbModemInterfaceName);
}
}
}
} catch (SocketException e) {
Log.e(LOG_TAG, "Tethering SocketException " + e.getMessage() + " " + e.getCause());
}
if (usbTetherOn && !new PrefManager(context).getBoolPref("ModemIsON")) {
new PrefManager(context).setBoolPref("ModemIsON", true);
ModulesStatus.getInstance().setIptablesRulesUpdateRequested(context, true);
} else if (!usbTetherOn && new PrefManager(context).getBoolPref("ModemIsON")) {
new PrefManager(context).setBoolPref("ModemIsON", false);
ModulesStatus.getInstance().setIptablesRulesUpdateRequested(context, true);
}
}
private static long initialSeed() {
String pp = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(
"java.util.secureRandomSeed"));
if (pp != null && pp.equalsIgnoreCase("true")) {
byte[] seedBytes = java.security.SecureRandom.getSeed(8);
long s = (long)(seedBytes[0]) & 0xffL;
for (int i = 1; i < 8; ++i)
s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
return s;
}
long h = 0L;
try {
Enumeration<NetworkInterface> ifcs =
NetworkInterface.getNetworkInterfaces();
boolean retry = false; // retry once if getHardwareAddress is null
while (ifcs.hasMoreElements()) {
NetworkInterface ifc = ifcs.nextElement();
if (!ifc.isVirtual()) { // skip fake addresses
byte[] bs = ifc.getHardwareAddress();
if (bs != null) {
int n = bs.length;
int m = Math.min(n >>> 1, 4);
for (int i = 0; i < m; ++i)
h = (h << 16) ^ (bs[i] << 8) ^ bs[n-1-i];
if (m < 4)
h = (h << 8) ^ bs[n-1-m];
h = mix64(h);
break;
}
else if (!retry)
retry = true;
else
break;
}
}
} catch (Exception ignore) {
}
return (h ^ mix64(System.currentTimeMillis()) ^
mix64(System.nanoTime()));
}