Example usage for java.net InetAddress getHostAddress

List of usage examples for java.net InetAddress getHostAddress

Introduction

In this page you can find the example usage for java.net InetAddress getHostAddress.

Prototype

public String getHostAddress() 

Source Link

Document

Returns the IP address string in textual presentation.

Usage

From source file:com.jkoolcloud.tnt4j.utils.Utils.java

/**
 * Determines the IP Address of the local server.
 *
 * @return string representation of IP Address
 *//*from   w w w . j  ava2s .  co  m*/
public static String getLocalHostAddress() {
    String hostIp = "127.0.0.1";
    InetAddress host;
    try {
        host = InetAddress.getLocalHost();
        hostIp = host.getHostAddress();
    } catch (UnknownHostException e) {
    }

    return hostIp;
}

From source file:edu.ucsd.crbs.cws.auth.UserIpAddressValidatorImpl.java

/**
 * Compares <b>requestAddress</b> against ipv4 CIDR in <b>cidrAddress</b>
 * @param requestAddress requestAddress ipv4 address of the request
 * @param cidrAddress ipv4 CIDR address/* w  ww. j av a  2 s.  c  o m*/
 * @return true if the <b>requestAddress</b> is within the range of the 
 * <b>cidrAddress</b>, false otherwise
 */
private boolean isIpv4AddressInCidrAddress(InetAddress requestAddress, final String cidrAddress) {
    try {
        SubnetUtils snUtils = new SubnetUtils(cidrAddress);
        return snUtils.getInfo().isInRange(requestAddress.getHostAddress());
    } catch (Exception ex) {
        _log.log(Level.WARNING, "Problems parsing cidr address: {0} and comparing to {1} : {2}",
                new Object[] { cidrAddress, requestAddress.getHostAddress(), ex.getMessage() });
    }
    return false;
}

From source file:org.onosproject.ospf.controller.impl.Controller.java

/**
 * Tell controller that we're ready to handle channels.
 *///from  w w  w .j  a v  a 2s.c om
public void run() {
    try {
        //get the configuration from json file
        List<OSPFArea> areas = getConfiguration();
        //get the connected interfaces
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        // Check NetworkInterfaces and area-config have same IP Address
        for (NetworkInterface netInt : Collections.list(nets)) {
            // if the interface is up & not loopback
            if (!netInt.isUp() && !netInt.isLoopback()) {
                continue;
            }
            //get all the InetAddresses
            Enumeration<InetAddress> inetAddresses = netInt.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                String ipAddress = inetAddress.getHostAddress();
                //Search for the address in all configured areas interfaces
                for (OSPFArea area : areas) {
                    for (OSPFInterface ospfIf : area.getInterfacesLst()) {
                        String ipFromConfig = ospfIf.getIpAddress();
                        if (ipFromConfig.trim().equals(ipAddress.trim())) {
                            log.debug("Both Config and Interface have ipAddress {} for area {}", ipAddress,
                                    area.getAreaID());
                            // if same IP address create
                            try {
                                log.debug("Creating ServerBootstrap for {} @ {}", ipAddress, ospfPort);

                                final ServerBootstrap bootstrap = createServerBootStrap();
                                bootstrap.setOption("reuseAddr", true);
                                bootstrap.setOption("child.keepAlive", true);
                                bootstrap.setOption("child.tcpNoDelay", true);
                                bootstrap.setOption("child.sendBufferSize", Controller.BUFFER_SIZE);

                                //Set the interface name in ospfInterface
                                ospfIf.setInterfaceName(netInt.getDisplayName());
                                //netInt.get
                                // passing OSPFArea and interface to pipelinefactory
                                ChannelPipelineFactory pfact = new OSPFPipelineFactory(this, null, area,
                                        ospfIf);
                                bootstrap.setPipelineFactory(pfact);
                                InetSocketAddress sa = new InetSocketAddress(InetAddress.getByName(ipAddress),
                                        ospfPort);

                                cg = new DefaultChannelGroup();
                                cg.add(bootstrap.bind(sa));

                                log.debug("Listening for connections on {}", sa);
                                //For testing. remove this
                                interfc = ospfIf;

                                //Start aging process
                                area.initializeDB();
                                area.initializeArea();
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        log.error("Error::Controller:: {}", e.getMessage());
    }
}

From source file:org.opendaylight.groupbasedpolicy.jsonrpc.RpcServer.java

public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   ww w.  j  a va2  s . c o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        logger.debug("New Passive channel created : " + ch.toString());
                        InetAddress address = ch.remoteAddress().getAddress();
                        int port = ch.remoteAddress().getPort();
                        String identifier = address.getHostAddress() + ":" + port;
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new JsonRpcDecoder(100000),
                                new StringEncoder(CharsetUtil.UTF_8));

                        handleNewConnection(identifier, ch);
                        logger.warn("Connected Node : " + identifier);
                    }
                });
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
        // Start the server.
        ChannelFuture f = b.bind(identity, listenPort).sync();
        String id = f.channel().localAddress().toString();
        logger.warn("Connected Node : " + id);

        this.channel = f.channel();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("Thread interrupted", e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.bleum.canton.loadpage.LoadPage.java

private void logIp(String urlStr, PrintWriter writer) {
    URL url;// w  w w  . j a  va  2s  .  co  m
    InetAddress address = null;
    try {
        url = new URL(urlStr);
        String host = url.getHost();
        address = InetAddress.getByName(host);
        String ip = address.getHostAddress();
        LOGGER.info("Ip address of " + urlStr + " is: " + ip);
        writer.print(urlStr + CSV_SEPERATOR);
        writer.print(ip + CSV_SEPERATOR);
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
    }

}

From source file:com.l2jfree.loginserver.manager.BanManager.java

/**
 * Adds the address to the ban list of the login server, with the given duration.
 * /*w w w .j a v a  2s. c om*/
 * @param address The Address to be banned.
 * @param expiration Timestamp in milliseconds when this ban expires
 * @throws UnknownHostException if the address is invalid.
 */
public void addBanForAddress(String address, long expiration) throws UnknownHostException {
    InetAddress netAddress = InetAddress.getByName(address);
    SubNet _net = new SubNet(netAddress.getHostAddress());
    if (expiration != 0)
        _bannedIps.put(_net, new BanInfo(_net, expiration));
    else
        _restrictedIps.put(_net, new BanInfo(_net, expiration));
}

From source file:com.castlemock.web.basis.web.mvc.controller.AbstractController.java

/**
 * The method returns the local address (Not link local address, not loopback address) which the server is deployed on.
 * If the method does not find any INet4Address that is neither link local address and loopback address, the method
 * will return the the address 127.0.0.1
 * @return Returns the local address or 127.0.0.1 if no address was found
 * @throws SocketException Upon failing to extract network interfaces
 *//*  w w  w.ja va  2 s .  c  o  m*/
public String getHostAddress() throws SocketException {
    if (endpointAddress != null && !endpointAddress.isEmpty()) {
        return endpointAddress;
    }

    final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    while (networkInterfaces.hasMoreElements()) {
        final NetworkInterface networkInterface = networkInterfaces.nextElement();
        final Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            final InetAddress address = addresses.nextElement();
            if (!address.isLinkLocalAddress() && !address.isLoopbackAddress()
                    && address instanceof Inet4Address) {
                return address.getHostAddress();
            }
        }
    }

    return LOCAL_ADDRESS;
}

From source file:net.pms.network.HTTPServer.java

@Override
public void run() {
    logger.info("Starting DLNA Server on host {} and port {}...", hostname, port);

    while (!stop) {
        try {// ww  w.j  a  v a2 s .  c o m
            Socket socket = serverSocket.accept();
            InetAddress inetAddress = socket.getInetAddress();
            String ip = inetAddress.getHostAddress();
            // basic IP filter: solntcev at gmail dot com
            boolean ignore = false;

            if (configuration.getIpFiltering().allowed(inetAddress)) {
                logger.trace("Receiving a request from: " + ip);
            } else {
                ignore = true;
                socket.close();
                logger.trace("Ignoring request from: " + ip);
            }

            if (!ignore) {
                RequestHandler request = new RequestHandler(socket);
                Thread thread = new Thread(request, "Request Handler");
                thread.start();
            }
        } catch (ClosedByInterruptException e) {
            stop = true;
        } catch (IOException e) {
            logger.debug("Caught exception", e);
        } finally {
            try {
                if (stop && serverSocket != null) {
                    serverSocket.close();
                }

                if (stop && serverSocketChannel != null) {
                    serverSocketChannel.close();
                }
            } catch (IOException e) {
                logger.debug("Caught exception", e);
            }
        }
    }
}

From source file:de.ecclesia.kipeto.RepositoryResolver.java

/**
 * Ermittelt anhand der Default-Repository-URL die IP-Adresse der
 * Netzwerkkarte, die Verbindung zum Repository hat.
 *//*from  w  w w. j  av a 2  s. c  om*/
private String determinateLocalIP() throws IOException {
    Socket socket = null;

    try {

        int port;
        String hostname;

        if (isSftp()) {
            port = 22;
            hostname = getHostname();
        } else {
            URL url = new URL(defaultRepositoryUrl);
            port = url.getPort() > -1 ? url.getPort() : url.getDefaultPort();
            hostname = url.getHost();
        }

        log.debug("Determinating local IP-Adress by connect to {}:{}", defaultRepositoryUrl, port);
        InetAddress address = Inet4Address.getByName(hostname);

        socket = new Socket();
        socket.connect(new InetSocketAddress(address, port), 3000);
        InputStream stream = socket.getInputStream();
        InetAddress localAddress = socket.getLocalAddress();
        stream.close();

        String localIp = localAddress.getHostAddress();

        log.info("Local IP-Adress is {}", localIp);

        return localIp;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:cc.arduino.packages.discoverers.NetworkDiscovery.java

@Override
public void serviceResolved(ServiceEvent serviceEvent) {
    int sleptFor = 0;
    while (BaseNoGui.packages == null && sleptFor <= MAX_TIME_AWAITING_FOR_PACKAGES) {
        try {/*w  ww.  ja  v  a  2 s.c o  m*/
            Thread.sleep(1000);
            sleptFor += 1000;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    ServiceInfo info = serviceEvent.getInfo();
    for (InetAddress inetAddress : info.getInet4Addresses()) {
        String address = inetAddress.getHostAddress();
        String name = serviceEvent.getName();

        BoardPort port = new BoardPort();

        String board = null;
        String description = null;
        if (info.hasData()) {
            board = info.getPropertyString("board");
            description = info.getPropertyString("description");
            port.getPrefs().put("board", board);
            port.getPrefs().put("distro_version", info.getPropertyString("distro_version"));
            port.getPrefs().put("port", "" + info.getPort());

            //Add additional fields to permit generic ota updates
            //and make sure we do not intefere with Arduino boards
            // define "ssh_upload=no" TXT property to use generic uploader
            // define "tcp_check=no" TXT property if you are not using TCP
            // define "auth_upload=yes" TXT property if you want to use authenticated generic upload
            String useSSH = info.getPropertyString("ssh_upload");
            String checkTCP = info.getPropertyString("tcp_check");
            String useAuth = info.getPropertyString("auth_upload");
            if (useSSH == null || !useSSH.contentEquals("no"))
                useSSH = "yes";
            if (checkTCP == null || !checkTCP.contentEquals("no"))
                checkTCP = "yes";
            if (useAuth == null || !useAuth.contentEquals("yes"))
                useAuth = "no";
            port.getPrefs().put("ssh_upload", useSSH);
            port.getPrefs().put("tcp_check", checkTCP);
            port.getPrefs().put("auth_upload", useAuth);
        }

        String label = name + " at " + address;
        if (board != null && BaseNoGui.packages != null) {
            String boardName = BaseNoGui.getPlatform().resolveDeviceByBoardID(BaseNoGui.packages, board);
            if (boardName != null) {
                label += " (" + boardName + ")";
            }
        } else if (description != null) {
            label += " (" + description + ")";
        }

        port.setAddress(address);
        port.setBoardName(name);
        port.setProtocol("network");
        port.setLabel(label);

        synchronized (boardPortsDiscoveredWithJmDNS) {
            removeDuplicateBoards(port);
            boardPortsDiscoveredWithJmDNS.add(port);
        }
    }
}