Java Code Examples for java.net.InterfaceAddress#getAddress()

The following examples show how to use java.net.InterfaceAddress#getAddress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NetworkPrefixLength.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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");
}
 
Example 2
Source File: NetworkPrefixLength.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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");
}
 
Example 3
Source File: TcpStorageServer.java    From crail with Apache License 2.0 6 votes vote down vote up
public static InetSocketAddress getDataNodeAddress() throws IOException {
	String ifname = TcpStorageConstants.STORAGE_TCP_INTERFACE;
	int port = TcpStorageConstants.STORAGE_TCP_PORT;
	
	NetworkInterface netif = NetworkInterface.getByName(ifname);
	if (netif == null){
		return null;
	}
	List<InterfaceAddress> addresses = netif.getInterfaceAddresses();
	InetAddress addr = null;
	for (InterfaceAddress address: addresses){
		if (address.getBroadcast() != null){
			InetAddress _addr = address.getAddress();
			addr = _addr;
		}
	}		
	InetSocketAddress inetAddr = new InetSocketAddress(addr, port);
	return inetAddr;
}
 
Example 4
Source File: NetworkPrefixLength.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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");
}
 
Example 5
Source File: NetworkHelper.java    From orWall with GNU General Public License v3.0 6 votes vote down vote up
public static String getMask(String intf){
    try {
        NetworkInterface ntwrk = NetworkInterface.getByName(intf);
        Iterator<InterfaceAddress> addrList = ntwrk.getInterfaceAddresses().iterator();
        while (addrList.hasNext()) {
            InterfaceAddress addr = addrList.next();
            InetAddress ip = addr.getAddress();
            if (ip instanceof Inet4Address) {
                String mask = ip.getHostAddress() + "/" +
                        addr.getNetworkPrefixLength();
                return mask;
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 6
Source File: WSDiscoveryClientTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
static NetworkInterface findIpv4Interface() throws Exception {
    Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces();
    List<NetworkInterface> possibles = new ArrayList<>();
    while (ifcs.hasMoreElements()) {
        NetworkInterface ni = ifcs.nextElement();
        if (ni.supportsMulticast()
            && ni.isUp()) {
            for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
                if (ia.getAddress() instanceof java.net.Inet4Address
                    && !ia.getAddress().isLoopbackAddress()
                    && !ni.getDisplayName().startsWith("vnic")) {
                    possibles.add(ni);
                }
            }
        }
    }
    return possibles.isEmpty() ? null : possibles.get(possibles.size() - 1);
}
 
Example 7
Source File: RemoteInterpreterUtils.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public static String findAvailableHostAddress() throws UnknownHostException, SocketException {
  String zeppelinServerIP = System.getenv("ZEPPELIN_LOCAL_IP");
  if (zeppelinServerIP != null) {
    return zeppelinServerIP;
  }

  InetAddress address = InetAddress.getLocalHost();
  if (address.isLoopbackAddress()) {
    for (NetworkInterface networkInterface : Collections
        .list(NetworkInterface.getNetworkInterfaces())) {
      if (!networkInterface.isLoopback()) {
        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
          InetAddress a = interfaceAddress.getAddress();
          if (a instanceof Inet4Address) {
            return a.getHostAddress();
          }
        }
      }
    }
  }
  return address.getHostAddress();
}
 
Example 8
Source File: IPv6ScopeIdMatchUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void processNetworkInterface(NetworkInterface nif) {
    for (InterfaceAddress ifaddr : nif.getInterfaceAddresses()) {
        InetAddress inetAddress = ifaddr.getAddress();
        if (inetAddress instanceof Inet6Address) {
            Inet6Address inet6 = (Inet6Address) inetAddress;
            if (inet6.isLoopbackAddress()) {
                loopbackInterface = nif;
                loopbackAddress = inet6;
            } else if (addresses.containsKey(nif)) {
                addresses.get(nif).add(inet6);
            } else {
                Set<Inet6Address> set = new HashSet<Inet6Address>();
                set.add(inet6);
                addresses.put(nif, set);
            }
        }
    }
}
 
Example 9
Source File: NetworkPrefixLength.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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");
}
 
Example 10
Source File: SolrMaster.java    From yarn-proto with Apache License 2.0 5 votes vote down vote up
protected String getMyInetAddresses() {
  Set<String> ipAddrs = new HashSet<String>();
  try {
    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
    while (ifaces.hasMoreElements()) {
      NetworkInterface next = ifaces.nextElement();
      for (InterfaceAddress addr : next.getInterfaceAddresses()) {
        InetAddress inetAddr = addr.getAddress();
        String ipAddr = inetAddr.getHostAddress();
        if (ipAddr != null && ipAddr.length() > 0) {
          // todo: use a regex
          if (!"127.0.0.1".equals(ipAddr) && (ipAddr.indexOf(".") != -1 && ipAddr.indexOf(":") == -1))
            ipAddrs.add(ipAddr);
        }
      }
    }
  } catch (Exception exc) {
    throw new RuntimeException("Failed to get address(es) of SolrMaster node due to: " + exc, exc);
  }
  StringBuilder addrs = new StringBuilder();
  for (String ip : ipAddrs) {
    if (addrs.length() > 0)
      addrs.append(",");
    addrs.append(ip);
  }

  return addrs.toString();
}
 
Example 11
Source File: RouteTools.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static String getBestInterfaceAddress() {
    // TODO how to give bluetooth preference?
    final List<InterfaceAddress> list = getLikelyInterfaceAddresses();
    String best = null;
    for (InterfaceAddress iaddr : list) {
        final InetAddress addr = iaddr.getAddress();
        if (addr.isLoopbackAddress()) continue;
        if (isLocal(addr)) {
            best = addr.getHostAddress();
            break; // grabs first one
        }
    }
    return best;
}
 
Example 12
Source File: NetworkPrefixLength.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static boolean checkPrefix(InterfaceAddress iaddr) {
    InetAddress addr = iaddr.getAddress();

    if (addr instanceof Inet4Address)
        return checkIPv4PrefixLength(iaddr.getNetworkPrefixLength());
    else
        return checkIPv6PrefixLength(iaddr.getNetworkPrefixLength());
}
 
Example 13
Source File: IfConfig.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/** format internet address: java's default doesn't include everything useful */
private static String formatAddress(InterfaceAddress interfaceAddress) throws IOException {
    StringBuilder sb = new StringBuilder();
    
    InetAddress address = interfaceAddress.getAddress();
    if (address instanceof Inet6Address) {
        sb.append("inet6 ");
        sb.append(NetworkAddress.formatAddress(address));
        sb.append(" prefixlen:");
        sb.append(interfaceAddress.getNetworkPrefixLength());
    } else {
        sb.append("inet ");
        sb.append(NetworkAddress.formatAddress(address));
        int netmask = 0xFFFFFFFF << (32 - interfaceAddress.getNetworkPrefixLength());
        sb.append(" netmask:" + NetworkAddress.formatAddress(InetAddress.getByAddress(new byte[] {
                (byte)(netmask >>> 24), 
                (byte)(netmask >>> 16 & 0xFF), 
                (byte)(netmask >>> 8 & 0xFF), 
                (byte)(netmask & 0xFF) 
        })));
        InetAddress broadcast = interfaceAddress.getBroadcast();
        if (broadcast != null) {
            sb.append(" broadcast:" + NetworkAddress.formatAddress(broadcast));
        }
    }
    if (address.isLoopbackAddress()) {
        sb.append(" scope:host");
    } else if (address.isLinkLocalAddress()) {
        sb.append(" scope:link");
    } else if (address.isSiteLocalAddress()) {
        sb.append(" scope:site");
    }
    return sb.toString();
}
 
Example 14
Source File: NetUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static String[] getNetworkParams(final NetworkInterface nic) {
    List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
    if (addrs == null || addrs.size() == 0) {
        return null;
    }
    Collections.reverse(addrs); // reverse addresses because it has reverse order as "ip addr show"
    InterfaceAddress addr = null;
    for (final InterfaceAddress iaddr : addrs) {
        final InetAddress inet = iaddr.getAddress();
        if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress() && inet.getAddress().length == 4) {
            addr = iaddr;
            break;
        }
    }
    if (addr == null) {
        return null;
    }
    final String[] result = new String[3];
    result[0] = addr.getAddress().getHostAddress();
    try {
        final byte[] mac = nic.getHardwareAddress();
        result[1] = byte2Mac(mac);
    } catch (final SocketException e) {
        s_logger.debug("Caught exception when trying to get the mac address ", e);
    }

    result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
    return result;
}
 
Example 15
Source File: NetUtil.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private @Nullable String getIPv4inSubnet(String ipAddress, String subnetMask) {
    try {
        final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            final NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
                continue;
            }

            for (InterfaceAddress ifAddr : current.getInterfaceAddresses()) {
                InetAddress addr = ifAddr.getAddress();

                if (addr.isLoopbackAddress() || (addr instanceof Inet6Address)) {
                    continue;
                }

                String ipv4AddressOnInterface = addr.getHostAddress();
                String subnetStringOnInterface = getIpv4NetAddress(ipv4AddressOnInterface,
                        ifAddr.getNetworkPrefixLength()) + "/" + String.valueOf(ifAddr.getNetworkPrefixLength());

                String configuredSubnetString = getIpv4NetAddress(ipAddress, Short.parseShort(subnetMask)) + "/"
                        + subnetMask;

                // use first IP within this subnet
                if (subnetStringOnInterface.equals(configuredSubnetString)) {
                    return ipv4AddressOnInterface;
                }
            }
        }
    } catch (SocketException ex) {
        LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
    }
    return null;
}
 
Example 16
Source File: NetworkPrefixLength.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static boolean checkPrefix(InterfaceAddress iaddr) {
    InetAddress addr = iaddr.getAddress();

    if (addr instanceof Inet4Address)
        return checkIPv4PrefixLength(iaddr.getNetworkPrefixLength());
    else
        return checkIPv6PrefixLength(iaddr.getNetworkPrefixLength());
}
 
Example 17
Source File: UDPDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
private NetworkInterface findNetworkInterface() throws SocketException {
    String name = (String)this.getEndpointInfo().getProperty(UDPDestination.NETWORK_INTERFACE);
    NetworkInterface ret = null;
    if (!StringUtils.isEmpty(name)) {
        ret = NetworkInterface.getByName(name);
    }
    if (ret == null) {
        Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces();
        List<NetworkInterface> possibles = new ArrayList<>();
        while (ifcs.hasMoreElements()) {
            NetworkInterface ni = ifcs.nextElement();
            if (ni.supportsMulticast()
                && ni.isUp()) {
                for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
                    if (ia.getAddress() instanceof java.net.Inet4Address
                        && !ia.getAddress().isLoopbackAddress()
                        && !ni.getDisplayName().startsWith("vnic")) {
                        possibles.add(ni);
                    }
                }
            }
        }
        ret = possibles.isEmpty() ? null : possibles.get(possibles.size() - 1);

    }
    return ret;
}
 
Example 18
Source File: RequestUtil.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * 获取服务器IP
 * --------------------------------------------------------------------------------------------------
 * 1.InetAddress.getLocalHost()在Windows下能获取到服务器IP,但Linux下获取到的就是127.0.0.1
 * 2.java.net.InterfaceAddress是JDK6.0新增的
 * 3.单网卡时会返回其IP,多网卡时会返回第一块网卡的IP
 * --------------------------------------------------------------------------------------------------
 */
public static String getServerIP(){
    String localAddress = "127.0.0.1";
    Map<String, String> SUBNET_MASK_MAP = new HashMap<String, String>(){
        private static final long serialVersionUID = 2303073623617570607L;
        {
            put("8", "255.0.0.0");
            put("16", "255.255.0.0");
            put("24", "255.255.255.0");
            put("128", "(::1/128");
            put("10", "fe80::203:baff:fe27:1243/10");
        }
    };
    String serverIP = "";
    try{
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        tag:while(nets.hasMoreElements()){
            NetworkInterface net = nets.nextElement();
            if(null != net.getHardwareAddress()){
                List<InterfaceAddress> addressList = net.getInterfaceAddresses();
                for(InterfaceAddress obj : addressList){
                    InetAddress IP = obj.getAddress();
                    if(IP instanceof Inet4Address && !localAddress.equals(IP.getHostAddress())){
                        serverIP = IP.getHostAddress();
                        LogUtil.getLogger().debug("IP=[{}]的子网掩码为=[{}]", serverIP, SUBNET_MASK_MAP.get(String.valueOf(obj.getNetworkPrefixLength())));
                        break tag;
                    }
                }
            }
        }
    }catch(SocketException e){
        LogUtil.getLogger().error("服务器IP地址获取失败,堆栈轨迹如下", e);
        serverIP = "服务器IP地址获取失败";
    }
    return serverIP;
}
 
Example 19
Source File: HostName.java    From IPAddress with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a host name from an InterfaceAddress.
 * 
 * @param interfaceAddr
 */
public HostName(InterfaceAddress interfaceAddr) {
	this(interfaceAddr.getAddress(), (int) interfaceAddr.getNetworkPrefixLength());
}
 
Example 20
Source File: LinkAddress.java    From android_9.0.0_r45 with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new {@code LinkAddress} from an {@code InterfaceAddress}.
 * The flags are set to zero and the scope is determined from the address.
 * @param interfaceAddress The interface address.
 * @hide
 */
public LinkAddress(InterfaceAddress interfaceAddress) {
    this(interfaceAddress.getAddress(),
         interfaceAddress.getNetworkPrefixLength());
}