Java Code Examples for java.net.InetAddress#isMulticastAddress()

The following examples show how to use java.net.InetAddress#isMulticastAddress() . These examples are extracted from open source projects. 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 Project: netty-4.1.22   File: MacAddressUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static int scoreAddress(InetAddress addr) {
    if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()) {
        return 0;
    }
    if (addr.isMulticastAddress()) {
        return 1;
    }
    if (addr.isLinkLocalAddress()) {
        return 2;
    }
    if (addr.isSiteLocalAddress()) {
        return 3;
    }

    return 4;
}
 
Example 2
public static String getHostName() throws SocketException {
  	Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
    NetworkInterface n = (NetworkInterface) e.nextElement();
    Enumeration<InetAddress> ee = n.getInetAddresses();
    while (ee.hasMoreElements())
    {
        InetAddress i = (InetAddress) ee.nextElement();
        if (!i.isSiteLocalAddress() && !i.isLinkLocalAddress() && !i.isLoopbackAddress() && !i.isAnyLocalAddress() && !i.isMulticastAddress()) {
        	return i.getHostName();
        }
    }
}
throw new SocketException("Failed to get the IP address for the local host");
  }
 
Example 3
ScuttlebuttLocalDiscoveryService(
    Vertx vertx,
    Logger logger,
    int listenPort,
    int broadcastPort,
    String listenNetworkInterface,
    String multicastAddress,
    boolean validateMulticast) {
  if (validateMulticast) {
    InetAddress multicastIP = InetAddresses.forString(multicastAddress);
    if (!multicastIP.isMulticastAddress()) {
      throw new IllegalArgumentException("Multicast address required, got " + multicastAddress);
    }
  }
  this.vertx = vertx;
  this.logger = logger;
  this.listenPort = listenPort;
  this.broadcastPort = broadcastPort;
  this.listenNetworkInterface = listenNetworkInterface;
  this.multicastAddress = multicastAddress;
}
 
Example 4
public static boolean isPrivate(String url) {

        try {
            InetAddress inetAddress = Inet6Address.getByName(new URL(url).getHost());

            return inetAddress.isSiteLocalAddress()
                    || inetAddress.isAnyLocalAddress()
                    || inetAddress.isLoopbackAddress()
                    || inetAddress.isLinkLocalAddress()
                    || inetAddress.isMulticastAddress()
                    || isPrivateOwasp(inetAddress.getHostAddress());

        } catch (Exception e) {

            throw new InvalidDataException("Url [" + url + "] is invalid");
        }
    }
 
Example 5
Source Project: actframework   File: LocalIpAddressUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取本地ip地址,有可能会有多个地址, 若有多个网卡则会搜集多个网卡的ip地址
 */
public static Set<InetAddress> resolveLocalAddresses() {
    Set<InetAddress> addrs = new HashSet<InetAddress>();
    Enumeration<NetworkInterface> ns = null;
    try {
        ns = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        // ignored...
    }
    while (ns != null && ns.hasMoreElements()) {
        NetworkInterface n = ns.nextElement();
        Enumeration<InetAddress> is = n.getInetAddresses();
        while (is.hasMoreElements()) {
            InetAddress i = is.nextElement();
            if (!i.isLoopbackAddress() && !i.isLinkLocalAddress() && !i.isMulticastAddress()
                    && !isSpecialIp(i.getHostAddress())) addrs.add(i);
        }
    }
    return addrs;
}
 
Example 6
private static boolean isIPv6GlobalAddress(InetAddress ip) {
    return (ip instanceof Inet6Address) &&
           !ip.isAnyLocalAddress() &&
           !ip.isLoopbackAddress() &&
           !ip.isLinkLocalAddress() &&
           !ip.isSiteLocalAddress() &&
           !ip.isMulticastAddress();
}
 
Example 7
Source Project: h2o-2   File: TimelineSnapshot.java    License: Apache License 2.0 5 votes vote down vote up
private boolean computeH2O(boolean b) {
  H2ONode h2o = null;
  if( dataLo() != 0 ) {     // Dead/initial packet
    InetAddress inet = addrPack();
    if( !inet.isMulticastAddress() ) { // Is multicast?
      h2o = H2ONode.intern(inet,portPack());
      if( isSend() && h2o == recoH2O() ) // Another multicast indicator: sending to self
        h2o = null;                      // Flag as multicast
    }
  }
  _packh2o = h2o;
  return b;                 // For flow-coding
}
 
Example 8
public static void checkMulticastAddress(InetAddress multicastAddress) {
    if (!multicastAddress.isMulticastAddress()) {
        String message = "Invalid multicast address " + multicastAddress;
        if (multicastAddress instanceof Inet4Address) {
            throw new IllegalArgumentException(message + ", " +
                "ipv4 multicast address scope: 224.0.0.0 - 239.255.255.255.");
        } else {
            throw new IllegalArgumentException(message + ", " + "ipv6 multicast address must start with ff, " +
                "for example: ff01::1");
        }
    }
}
 
Example 9
Source Project: cloudstack   File: UriUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Pair<String, Integer> validateUrl(String format, String url) throws IllegalArgumentException {
    try {
        URI uri = new URI(url);
        if ((uri.getScheme() == null) ||
                (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https") && !uri.getScheme().equalsIgnoreCase("file"))) {
            throw new IllegalArgumentException("Unsupported scheme for url: " + url);
        }

        int port = uri.getPort();
        if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) {
            port = 443;
        } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) {
            port = 80;
        }

        String host = uri.getHost();
        try {
            InetAddress hostAddr = InetAddress.getByName(host);
            if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) {
                throw new IllegalArgumentException("Illegal host specified in url");
            }
            if (hostAddr instanceof Inet6Address) {
                throw new IllegalArgumentException("IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")");
            }
        } catch (UnknownHostException uhe) {
            throw new IllegalArgumentException("Unable to resolve " + host);
        }

        // verify format
        if (format != null) {
            String uripath = uri.getPath();
            checkFormat(format, uripath);
        }
        return new Pair<String, Integer>(host, port);
    } catch (URISyntaxException use) {
        throw new IllegalArgumentException("Invalid URL: " + url);
    }
}
 
Example 10
Source Project: onos   File: IPv6AddressTlv.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reads the channel buffer and returns object of IPv6AddressTlv.
 *
 * @param cb channelBuffer
 * @param type address type
 * @return object of IPv6AddressTlv
 * @throws BgpParseException while parsing IPv6AddressTlv
 */
public static IPv6AddressTlv read(ChannelBuffer cb, short type) throws BgpParseException {
    InetAddress ipAddress = Validation.toInetAddress(LENGTH, cb);
    if (ipAddress.isMulticastAddress()) {
        throw new BgpParseException(BgpErrorType.UPDATE_MESSAGE_ERROR, (byte) 0, null);
    }
    Ip6Address address = Ip6Address.valueOf(ipAddress);
    return IPv6AddressTlv.of(address, type);
}
 
Example 11
Source Project: xmrwallet   File: PeerRetriever.java    License: Apache License 2.0 5 votes vote down vote up
private void readAddressList(Section section) {
    Section data = (Section) section.get("payload_data");
    int topVersion = (Integer) data.get("top_version");
    long currentHeight = (Long) data.get("current_height");
    String topId = HexHelper.bytesToHex((byte[]) data.get("top_id"));
    Timber.d("PAYLOAD_DATA %d/%d/%s", topVersion, currentHeight, topId);

    @SuppressWarnings("unchecked")
    List<Section> peerList = (List<Section>) section.get("local_peerlist_new");
    if (peerList != null) {
        for (Section peer : peerList) {
            Section adr = (Section) peer.get("adr");
            Integer type = (Integer) adr.get("type");
            if ((type == null) || (type != 1))
                continue;
            Section addr = (Section) adr.get("addr");
            if (addr == null)
                continue;
            Integer ip = (Integer) addr.get("m_ip");
            if (ip == null)
                continue;
            Integer sport = (Integer) addr.get("m_port");
            if (sport == null)
                continue;
            int port = sport;
            if (port < 0) // port is unsigned
                port = port + 0x10000;
            InetAddress inet = HexHelper.toInetAddress(ip);
            // make sure this is an address we want to talk to (i.e. a remote address)
            if (!inet.isSiteLocalAddress() && !inet.isAnyLocalAddress()
                    && !inet.isLoopbackAddress()
                    && !inet.isMulticastAddress()
                    && !inet.isLinkLocalAddress()) {
                peers.add(new LevinPeer(inet, port, topVersion, currentHeight, topId));
            }
        }
    }
}
 
Example 12
Source Project: dhcp4j   File: AddressUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether the given address is a "useful" unicast address.
 *
 * Site local is allowed. Loopback is not.
 */
public static boolean isUnicastAddress(@CheckForNull InetAddress address) {
    return (address != null)
            && !address.isAnyLocalAddress()
            && !address.isLoopbackAddress()
            && !address.isMulticastAddress();
}
 
Example 13
Source Project: cosmic   File: NetUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String[] getNetworkParams(final NetworkInterface nic) {
    final List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
    if (addrs == null || addrs.size() == 0) {
        return null;
    }
    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 14
Source Project: mpush   File: UDPChannelHandler.java    License: Apache License 2.0 5 votes vote down vote up
public UDPChannelHandler setMulticastAddress(InetAddress multicastAddress) {
    if (!multicastAddress.isMulticastAddress()) {
        throw new IllegalArgumentException(multicastAddress + "not a multicastAddress");
    }

    this.multicastAddress = multicastAddress;
    return this;
}
 
Example 15
Source Project: tomee   File: MulticastPulseAgentTest.java    License: Apache License 2.0 5 votes vote down vote up
private static InetAddress getAddress(final String host) throws Exception {
    final InetAddress ia;
    try {
        ia = InetAddress.getByName(host);
    } catch (final UnknownHostException e) {
        throw new Exception(host + " is not a valid address", e);
    }

    if (null == ia || !ia.isMulticastAddress()) {
        throw new Exception(host + " is not a valid multicast address");
    }
    return ia;
}
 
Example 16
Source Project: geowave   File: ApiRestletApplication.java    License: Apache License 2.0 5 votes vote down vote up
private static String getHTTPEndPoint() throws Exception {
  final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
  final QueryExp subQuery1 = Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"));
  final QueryExp subQuery2 = Query.anySubString(Query.attr("protocol"), Query.value("Http11"));
  final QueryExp query = Query.or(subQuery1, subQuery2);
  final Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"), query);
  // HP Fortify "DNS Lookups" false positive
  // The DNS lookups referenced here are not used for Security purposes
  final String hostname = InetAddress.getLocalHost().getHostName();
  // HP Fortify "DNS Lookups" false positive
  // The DNS lookups referenced here are not used for Security purposes
  final InetAddress[] addresses = InetAddress.getAllByName(hostname);
  for (final Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {
    final ObjectName obj = i.next();
    // final String scheme = mbs.getAttribute(
    // obj,
    // "scheme").toString();
    final String port = obj.getKeyProperty("port");
    // HP Fortify "DNS Lookups" false positive
    // The DNS lookups referenced here are not used for Security
    // purposes
    for (final InetAddress addr : addresses) {
      if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isMulticastAddress()) {
        continue;
      }
      final String host = addr.getHostAddress();
      // just return the first one
      return host + ":" + port;
    }
    return hostname + ":" + port;
  }
  return "localhost:8080";
}
 
Example 17
protected void checkMcastAddress(InetAddress value) {
  _checkIfModifiable(MCAST_ADDRESS_NAME);
  if (!value.isMulticastAddress()) {
    throw new IllegalArgumentException(LocalizedStrings.AbstractDistributionConfig_COULD_NOT_SET_0_TO_1_BECAUSE_IT_WAS_NOT_A_MULTICAST_ADDRESS.toLocalizedString(new Object[] {MCAST_ADDRESS_NAME, value}));
  }
}
 
Example 18
Source Project: jesos   File: NetworkUtil.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean isGoodAddress(final InetAddress address)
{
    return !address.isAnyLocalAddress() &&
        !address.isLoopbackAddress() &&
        !address.isMulticastAddress();
}
 
Example 19
@SuppressWarnings("unchecked")
@Override
public JSONObject enrich(String metadata) {

	ResultSet resultSet = null;

	try {

		_LOG.trace("[OpenSOC] Received metadata: " + metadata);

		InetAddress addr = InetAddress.getByName(metadata);

		if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()
				|| addr.isSiteLocalAddress() || addr.isMulticastAddress()
				|| !ipvalidator.isValidInet4Address(metadata)) {
			_LOG.trace("[OpenSOC] Not a remote IP: " + metadata);
			_LOG.trace("[OpenSOC] Returning enrichment: " + "{}");

			return new JSONObject();
		}

		_LOG.trace("[OpenSOC] Is a valid remote IP: " + metadata);

		statement = connection.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE,
				ResultSet.CONCUR_READ_ONLY);
		String locid_query = "select IPTOLOCID(\"" + metadata
				+ "\") as ANS";
		resultSet = statement.executeQuery(locid_query);

		if (resultSet == null)
			throw new Exception("Invalid result set for metadata: "
					+ metadata + ". Query run was: " + locid_query);

		resultSet.last();
		int size = resultSet.getRow();

		if (size == 0)
			throw new Exception("No result returned for: " + metadata
					+ ". Query run was: " + locid_query);

		resultSet.beforeFirst();
		resultSet.next();

		String locid = null;
		locid = resultSet.getString("ANS");

		if (locid == null)
			throw new Exception("Invalid location id for: " + metadata
					+ ". Query run was: " + locid_query);

		String geo_query = "select * from location where locID = " + locid
				+ ";";
		resultSet = statement.executeQuery(geo_query);

		if (resultSet == null)
			throw new Exception(
					"Invalid result set for metadata and locid: "
							+ metadata + ", " + locid + ". Query run was: "
							+ geo_query);

		resultSet.last();
		size = resultSet.getRow();

		if (size == 0)
			throw new Exception(
					"No result id returned for metadata and locid: "
							+ metadata + ", " + locid + ". Query run was: "
							+ geo_query);

		resultSet.beforeFirst();
		resultSet.next();

		JSONObject jo = new JSONObject();
		jo.put("locID", resultSet.getString("locID"));
		jo.put("country", resultSet.getString("country"));
		jo.put("city", resultSet.getString("city"));
		jo.put("postalCode", resultSet.getString("postalCode"));
		jo.put("latitude", resultSet.getString("latitude"));
		jo.put("longitude", resultSet.getString("longitude"));
		jo.put("dmaCode", resultSet.getString("dmaCode"));
		jo.put("locID", resultSet.getString("locID"));
		
		jo.put("location_point", jo.get("longitude") + "," + jo.get("latitude"));

		_LOG.debug("Returning enrichment: " + jo);

		return jo;

	} catch (Exception e) {
		e.printStackTrace();
		_LOG.error("Enrichment failure: " + e);
		return new JSONObject();
	}
}
 
Example 20
Source Project: Bytecoder   File: DatagramChannelImpl.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Connects the channel's socket.
 *
 * @param sa the remote address to which this channel is to be connected
 * @param check true to check if the channel is already connected.
 */
DatagramChannel connect(SocketAddress sa, boolean check) throws IOException {
    InetSocketAddress isa = Net.checkAddress(sa, family);
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        InetAddress ia = isa.getAddress();
        if (ia.isMulticastAddress()) {
            sm.checkMulticast(ia);
        } else {
            sm.checkConnect(ia.getHostAddress(), isa.getPort());
            sm.checkAccept(ia.getHostAddress(), isa.getPort());
        }
    }

    readLock.lock();
    try {
        writeLock.lock();
        try {
            synchronized (stateLock) {
                ensureOpen();
                if (check && state == ST_CONNECTED)
                    throw new AlreadyConnectedException();

                // ensure that the socket is bound
                if (localAddress == null) {
                    bindInternal(null);
                }

                // capture local address before connect
                initialLocalAddress = localAddress;

                int n = Net.connect(family,
                                    fd,
                                    isa.getAddress(),
                                    isa.getPort());
                if (n <= 0)
                    throw new Error();      // Can't happen

                // connected
                remoteAddress = isa;
                state = ST_CONNECTED;

                // refresh local address
                localAddress = Net.localAddress(fd);

                // flush any packets already received.
                boolean blocking = isBlocking();
                if (blocking) {
                    IOUtil.configureBlocking(fd, false);
                }
                try {
                    ByteBuffer buf = ByteBuffer.allocate(100);
                    while (receive(buf, false) >= 0) {
                        buf.clear();
                    }
                } finally {
                    if (blocking) {
                        IOUtil.configureBlocking(fd, true);
                    }
                }
            }
        } finally {
            writeLock.unlock();
        }
    } finally {
        readLock.unlock();
    }
    return this;
}