Search in sources :

Example 76 with Inet4Address

use of java.net.Inet4Address in project jdk8u_jdk by JetBrains.

the class SdpProvider method loadRulesFromFile.

// loads rules from the given file
// Each non-blank/non-comment line must have the format:
// ("bind" | "connect") 1*LWSP-char (hostname | ipaddress["/" prefix])
//     1*LWSP-char ("*" | port) [ "-" ("*" | port) ]
private static List<Rule> loadRulesFromFile(String file) throws IOException {
    Scanner scanner = new Scanner(new File(file));
    try {
        List<Rule> result = new ArrayList<Rule>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            // skip blank lines and comments
            if (line.length() == 0 || line.charAt(0) == '#')
                continue;
            // must have 3 fields
            String[] s = line.split("\\s+");
            if (s.length != 3) {
                fail("Malformed line '%s'", line);
                continue;
            }
            // first field is the action ("bind" or "connect")
            Action action = null;
            for (Action a : Action.values()) {
                if (s[0].equalsIgnoreCase(a.name())) {
                    action = a;
                    break;
                }
            }
            if (action == null) {
                fail("Action '%s' not recognized", s[0]);
                continue;
            }
            // * port[-end]
            int[] ports = parsePortRange(s[2]);
            if (ports.length == 0) {
                fail("Malformed port range '%s'", s[2]);
                continue;
            }
            // match all addresses
            if (s[1].equals("*")) {
                result.add(new PortRangeRule(action, ports[0], ports[1]));
                continue;
            }
            // hostname | ipaddress[/prefix]
            int pos = s[1].indexOf('/');
            try {
                if (pos < 0) {
                    // hostname or ipaddress (no prefix)
                    InetAddress[] addresses = InetAddress.getAllByName(s[1]);
                    for (InetAddress address : addresses) {
                        int prefix = (address instanceof Inet4Address) ? 32 : 128;
                        result.add(new AddressPortRangeRule(action, address, prefix, ports[0], ports[1]));
                    }
                } else {
                    // ipaddress/prefix
                    InetAddress address = InetAddress.getByName(s[1].substring(0, pos));
                    int prefix = -1;
                    try {
                        prefix = Integer.parseInt(s[1].substring(pos + 1));
                        if (address instanceof Inet4Address) {
                            // must be 1-31
                            if (prefix < 0 || prefix > 32)
                                prefix = -1;
                        } else {
                            // must be 1-128
                            if (prefix < 0 || prefix > 128)
                                prefix = -1;
                        }
                    } catch (NumberFormatException e) {
                    }
                    if (prefix > 0) {
                        result.add(new AddressPortRangeRule(action, address, prefix, ports[0], ports[1]));
                    } else {
                        fail("Malformed prefix '%s'", s[1]);
                        continue;
                    }
                }
            } catch (UnknownHostException uhe) {
                fail("Unknown host or malformed IP address '%s'", s[1]);
                continue;
            }
        }
        return result;
    } finally {
        scanner.close();
    }
}
Also used : GetPropertyAction(sun.security.action.GetPropertyAction) Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) File(java.io.File) InetAddress(java.net.InetAddress)

Example 77 with Inet4Address

use of java.net.Inet4Address in project JMRI by JMRI.

the class ZeroConfService method publish.

/**
     * Start advertising the service.
     */
public void publish() {
    if (!isPublished()) {
        ZeroConfService.services.put(this.key(), this);
        this.listeners.stream().forEach((listener) -> {
            listener.serviceQueued(new ZeroConfServiceEvent(this, null));
        });
        boolean useIPv4 = ProfileUtils.getPreferences(ProfileManager.getDefault().getActiveProfile(), ZeroConfService.class, false).getBoolean(ZeroConfService.IPv4, true);
        boolean useIPv6 = ProfileUtils.getPreferences(ProfileManager.getDefault().getActiveProfile(), ZeroConfService.class, false).getBoolean(ZeroConfService.IPv6, true);
        for (JmDNS netService : ZeroConfService.netServices().values()) {
            ZeroConfServiceEvent event;
            ServiceInfo info;
            try {
                if (netService.getInetAddress() instanceof Inet6Address && !useIPv6) {
                    // Skip if address is IPv6 and should not be advertised on
                    log.debug("Ignoring IPv6 address {}", netService.getInetAddress().getHostAddress());
                    continue;
                }
                if (netService.getInetAddress() instanceof Inet4Address && !useIPv4) {
                    // Skip if address is IPv4 and should not be advertised on
                    log.debug("Ignoring IPv4 address {}", netService.getInetAddress().getHostAddress());
                    continue;
                }
                try {
                    log.debug("Publishing ZeroConfService for '{}' on {}", key(), netService.getInetAddress().getHostAddress());
                } catch (IOException ex) {
                    log.debug("Publishing ZeroConfService for '{}' with IOException {}", key(), ex.getLocalizedMessage(), ex);
                }
                // JmDNS requires a 1-to-1 mapping of serviceInfo to InetAddress
                if (!this.serviceInfos.containsKey(netService.getInetAddress())) {
                    try {
                        info = this.serviceInfo();
                        netService.registerService(info);
                        log.debug("Register service '{}' on {} successful.", this.key(), netService.getInetAddress().getHostAddress());
                    } catch (IllegalStateException ex) {
                        // thrown if the reference serviceInfo object is in use
                        try {
                            log.debug("Initial attempt to register '{}' on {} failed.", this.key(), netService.getInetAddress().getHostAddress());
                            info = this.addServiceInfo(netService);
                            log.debug("Retrying register '{}' on {}.", this.key(), netService.getInetAddress().getHostAddress());
                            netService.registerService(info);
                        } catch (IllegalStateException ex1) {
                            // thrown if service gets registered on interface by
                            // the networkListener before this loop on interfaces
                            // completes, so we only ensure a later notification
                            // is not posted continuing to next interface in list
                            log.debug("'{}' is already registered on {}.", this.key(), netService.getInetAddress().getHostAddress());
                            continue;
                        }
                    }
                } else {
                    log.debug("skipping '{}' on {}, already in serviceInfos.", this.key(), netService.getInetAddress().getHostAddress());
                }
                event = new ZeroConfServiceEvent(this, netService);
            } catch (IOException ex) {
                log.error("Unable to publish service for '{}': {}", key(), ex.getMessage());
                continue;
            }
            this.listeners.stream().forEach((listener) -> {
                listener.servicePublished(event);
            });
        }
    }
}
Also used : ServiceInfo(javax.jmdns.ServiceInfo) Inet4Address(java.net.Inet4Address) JmDNS(javax.jmdns.JmDNS) Inet6Address(java.net.Inet6Address) IOException(java.io.IOException)

Example 78 with Inet4Address

use of java.net.Inet4Address in project galley by Commonjava.

the class FastLocalCacheProvider method getCurrentNodeIp.

private String getCurrentNodeIp() throws SocketException {
    final Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
    while (nis.hasMoreElements()) {
        final NetworkInterface ni = nis.nextElement();
        final Enumeration<InetAddress> ips = ni.getInetAddresses();
        while (ips.hasMoreElements()) {
            final InetAddress ip = ips.nextElement();
            if (ip instanceof Inet4Address && ip.isSiteLocalAddress()) {
                return ip.getHostAddress();
            }
        }
    }
    throw new IllegalStateException("[galley] IP not found.");
}
Also used : Inet4Address(java.net.Inet4Address) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 79 with Inet4Address

use of java.net.Inet4Address in project sling by apache.

the class ReferrerFilter method getDefaultAllowedReferrers.

/**
     * Create a default list of referrers
     */
private Set<String> getDefaultAllowedReferrers() {
    final Set<String> referrers = new HashSet<String>();
    try {
        final Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
        while (ifaces.hasMoreElements()) {
            final NetworkInterface iface = ifaces.nextElement();
            logger.info("Adding Allowed referers for Interface:" + iface.getDisplayName());
            final Enumeration<InetAddress> ias = iface.getInetAddresses();
            while (ias.hasMoreElements()) {
                final InetAddress ia = ias.nextElement();
                final String address = ia.getHostAddress().trim().toLowerCase();
                if (ia instanceof Inet4Address) {
                    referrers.add("http://" + address + ":0");
                    referrers.add("https://" + address + ":0");
                }
                if (ia instanceof Inet6Address) {
                    referrers.add("http://[" + address + "]" + ":0");
                    referrers.add("https://[" + address + "]" + ":0");
                }
            }
        }
    } catch (final SocketException se) {
        logger.error("Unable to detect network interfaces", se);
    }
    referrers.add("http://localhost" + ":0");
    referrers.add("http://127.0.0.1" + ":0");
    referrers.add("http://[::1]" + ":0");
    referrers.add("https://localhost" + ":0");
    referrers.add("https://127.0.0.1" + ":0");
    referrers.add("https://[::1]" + ":0");
    return referrers;
}
Also used : SocketException(java.net.SocketException) Inet4Address(java.net.Inet4Address) NetworkInterface(java.net.NetworkInterface) Inet6Address(java.net.Inet6Address) InetAddress(java.net.InetAddress) HashSet(java.util.HashSet)

Example 80 with Inet4Address

use of java.net.Inet4Address in project trex-stateless-gui by cisco-system-traffic-generator.

the class PacketUpdater method updateDstAddress.

/**
     * Update destination IP address
     */
private Packet updateDstAddress(Packet packet) {
    try {
        if (importedProperties.isDestinationEnabled()) {
            Inet4Address modifiedAddress = (Inet4Address) Inet4Address.getByAddress(convertIPToByte(importedProperties.getDstAddress()));
            Packet.Builder builder = packet.getBuilder();
            if (packet.get(IpV4Packet.class).getHeader().getDstAddr().getHostAddress().equals(defaultDstAddress)) {
                builder.get(IpV4Packet.Builder.class).dstAddr(modifiedAddress);
            } else {
                builder.get(IpV4Packet.Builder.class).srcAddr(modifiedAddress);
            }
            packet = builder.build();
        }
    } catch (Exception ex) {
        LOG.error("Error updating destination IP", ex);
    }
    return packet;
}
Also used : Packet(org.pcap4j.packet.Packet) TcpPacket(org.pcap4j.packet.TcpPacket) IpV4Packet(org.pcap4j.packet.IpV4Packet) UdpPacket(org.pcap4j.packet.UdpPacket) Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException)

Aggregations

Inet4Address (java.net.Inet4Address)184 InetAddress (java.net.InetAddress)85 Inet6Address (java.net.Inet6Address)45 NetworkInterface (java.net.NetworkInterface)39 UnknownHostException (java.net.UnknownHostException)28 LinkAddress (android.net.LinkAddress)24 SocketException (java.net.SocketException)23 IOException (java.io.IOException)22 ArrayList (java.util.ArrayList)19 InterfaceAddress (java.net.InterfaceAddress)17 ByteBuffer (java.nio.ByteBuffer)17 RouteInfo (android.net.RouteInfo)12 LinkProperties (android.net.LinkProperties)7 InetSocketAddress (java.net.InetSocketAddress)6 Test (org.junit.Test)6 WifiDisplay (android.hardware.display.WifiDisplay)5 WifiDisplaySessionInfo (android.hardware.display.WifiDisplaySessionInfo)5 DhcpResults (android.net.DhcpResults)5 IpConfiguration (android.net.IpConfiguration)5 IpAssignment (android.net.IpConfiguration.IpAssignment)5