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.carreygroup.JARVIS.Demon.java

/******************************TCP
 * @throws UnknownHostException ******************************/
public boolean Connection(byte mode, String argv1, String argv2) throws UnknownHostException {
    Ethnet_Mode = mode;/*from  w w w  .  j  ava  2 s .c  o  m*/
    if (Ethnet_Mode == Ethnet.P2P) {
        P2PConnect(argv1, argv2);

    } else if (Ethnet_Mode == Ethnet.TCP) {
        //,IP
        java.net.InetAddress x;
        x = java.net.InetAddress.getByName(argv1);
        String host = x.getHostAddress();//ip      

        int port = Integer.valueOf(argv2);
        try {
            mSocket = new Socket();
            mAddress = new InetSocketAddress(host, port);
            mSocket.connect(mAddress, 5000);
            mPrintWriterClient = new PrintWriter(mSocket.getOutputStream(), true);
            if (mSocket.isConnected())
                Log.v("_DEBUG", "Connected!");
            else
                Log.v("_DEBUG", "No Connected!");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //  
        // new Thread(new ActiveTest(mSocket.socket())).start();
    } else if (Ethnet_Mode == Ethnet.UDP) {
        //,IP
        java.net.InetAddress x;
        x = java.net.InetAddress.getByName(argv1);
        String host = x.getHostAddress();//ip      
        int port = Integer.valueOf(argv2);

        mAddress = new InetSocketAddress(host, port);
        try {
            mSendPSocket = new DatagramSocket();
            mSendPSocket.setBroadcast(true);
            mReceviedSocket = new DatagramSocket(port);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

    if (Connected()) {
        for (ConnectionListener listener : mConnListeners) {
            listener.onConnected(this);
        }
    }
    return Connected();
}

From source file:com.photon.phresco.framework.impl.CIManagerImpl.java

public void setMailCredential(CIJob job) {
    S_LOGGER.debug("Entering Method CIManagerImpl.setMailCredential");
    try {//  w w w . j  a v  a2s .  c o  m
        InputStream credentialXml = PhrescoFrameworkFactory.getServiceManager().getMailerXml();
        SvnProcessor processor = new SvnProcessor(credentialXml);
        DataInputStream in = new DataInputStream(credentialXml);
        while (in.available() != 0) {
            System.out.println(in.readLine());
        }

        in.close();
        // Mail have to with jenkins running email address
        InetAddress ownIP = InetAddress.getLocalHost();
        processor.changeNodeValue(CI_HUDSONURL, HTTP_PROTOCOL + PROTOCOL_POSTFIX + ownIP.getHostAddress()
                + COLON + job.getJenkinsPort() + FORWARD_SLASH + CI + FORWARD_SLASH);
        processor.changeNodeValue("smtpAuthUsername", job.getSenderEmailId());
        processor.changeNodeValue("smtpAuthPassword", job.getSenderEmailPassword());
        processor.changeNodeValue("adminAddress", job.getSenderEmailId());

        //jenkins home location
        String jenkinsJobHome = System.getenv(JENKINS_HOME);
        StringBuilder builder = new StringBuilder(jenkinsJobHome);
        builder.append(File.separator);

        processor.writeStream(new File(builder.toString() + CI_MAILER_XML));
    } catch (Exception e) {
        S_LOGGER.error(
                "Entered into the catch block of CIManagerImpl.setMailCredential " + e.getLocalizedMessage());
    }
}

From source file:org.opendaylight.ovsdb.plugin.ConnectionService.java

private void ovsdbManager() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from   w w w .  j av  a 2 s  . co 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 channel) throws Exception {
                        logger.debug("New Passive channel created : " + channel.toString());
                        InetAddress address = channel.remoteAddress().getAddress();
                        int port = channel.remoteAddress().getPort();
                        String identifier = address.getHostAddress() + ":" + port;
                        channel.pipeline().addLast(new LoggingHandler(LogLevel.INFO),
                                new JsonRpcDecoder(100000), new StringEncoder(CharsetUtil.UTF_8));

                        Node node = handleNewConnection(identifier, channel, ConnectionService.this);
                        logger.debug("Connected Node : " + node.toString());
                    }
                });
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535));
        // Start the server.
        ChannelFuture f = b.bind(ovsdbListenPort).sync();
        serverListenChannel = f.channel();
        // Wait until the server socket is closed.
        serverListenChannel.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.l2jfree.loginserver.manager.LoginManager.java

/**
 * //  w ww.ja  v a2  s .  co m
 * If login are different, increment hackProtection counter. It's maybe a hacking attempt
 * 
 * @param user
 * @param password
 * @param address
 */
private void handleBadLogin(String user, String password, InetAddress address) {
    _logLoginFailed.info(
            "login failed for user : '" + user + "' " + (address == null ? "null" : address.getHostAddress()));

    // In special case, adress is null, so this protection is useless
    if (address != null) {
        FailedLoginAttempt failedAttempt = _hackProtection.get(address);
        int failedCount;
        if (failedAttempt == null) {
            _hackProtection.put(address, new FailedLoginAttempt(address, password));
            failedCount = 1;
        } else {
            failedAttempt.increaseCounter(password);
            failedCount = failedAttempt.getCount();
        }

        if (failedCount >= Config.LOGIN_TRY_BEFORE_BAN) {
            _log.info("Temporary auto-ban for " + address.getHostAddress() + " (" + Config.LOGIN_BLOCK_AFTER_BAN
                    + " seconds, " + failedCount + " login tries)");
            BanManager.getInstance().addBanForAddress(address, Config.LOGIN_BLOCK_AFTER_BAN * 1000);
        }
    }
}

From source file:sce.RESTAppMetricJob.java

public void sendEmail(JobExecutionContext context, String email) throws JobExecutionException {
    try {/*from ww w.  ja va  2 s.c o m*/
        Date d = new Date();
        String message = "Job was executed at: " + d.toString() + "\n";
        SchedulerMetaData schedulerMetadata = context.getScheduler().getMetaData();
        //Get the scheduler instance id
        message += "Scheduler Instance Id: " + schedulerMetadata.getSchedulerInstanceId() + "\n";
        //Get the scheduler name
        message += "Scheduler Name: " + schedulerMetadata.getSchedulerName() + "\n";
        try {
            //Get the scheduler ip
            Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
            message += "Scheduler IP: ";
            for (; n.hasMoreElements();) {
                NetworkInterface e = n.nextElement();
                //System.out.println("Interface: " + e.getName());
                Enumeration<InetAddress> a = e.getInetAddresses();
                for (; a.hasMoreElements();) {
                    InetAddress addr = a.nextElement();
                    message += !addr.getHostAddress().equals("127.0.0.1") ? addr.getHostAddress() + " " : "";
                }
            }
            message += "\n";
        } catch (SocketException e) {
            throw new JobExecutionException(e);
        }
        //Returns the result (if any) that the Job set before its execution completed (the type of object set as the result is entirely up to the particular job).
        //The result itself is meaningless to Quartz, but may be informative to JobListeners or TriggerListeners that are watching the job's execution. 
        message += "Result: " + (context.getResult() != null ? context.getResult() : "") + "\n";
        //Get the unique Id that identifies this particular firing instance of the trigger that triggered this job execution. It is unique to this JobExecutionContext instance as well. 
        message += "Fire Instance Id: "
                + (context.getFireInstanceId() != null ? context.getFireInstanceId() : "") + "\n";
        //Get a handle to the Calendar referenced by the Trigger instance that fired the Job. 
        message += "Calendar: " + (context.getCalendar() != null ? context.getCalendar().getDescription() : "")
                + "\n";
        //The actual time the trigger fired. For instance the scheduled time may have been 10:00:00 but the actual fire time may have been 10:00:03 if the scheduler was too busy. 
        message += "Fire Time: " + (context.getFireTime() != null ? context.getFireTime() : "") + "\n";
        //the job name
        message += "Job Name: "
                + (context.getJobDetail().getKey() != null ? context.getJobDetail().getKey().getName() : "")
                + "\n";
        //the job group
        message += "Job Group: "
                + (context.getJobDetail().getKey() != null ? context.getJobDetail().getKey().getGroup() : "")
                + "\n";
        //The amount of time the job ran for (in milliseconds). The returned value will be -1 until the job has actually completed (or thrown an exception), and is therefore generally only useful to JobListeners and TriggerListeners.
        //message += "RunTime: " + context.getJobRunTime() + "\n";
        //the next fire time
        message += "Next Fire Time: "
                + (context.getNextFireTime() != null && context.getNextFireTime().toString() != null
                        ? context.getNextFireTime().toString()
                        : "")
                + "\n";
        //the previous fire time
        message += "Previous Fire Time: "
                + (context.getPreviousFireTime() != null && context.getPreviousFireTime().toString() != null
                        ? context.getPreviousFireTime().toString()
                        : "")
                + "\n";
        //refire count
        message += "Refire Count: " + context.getRefireCount() + "\n";

        //job data map
        message += "\nJob data map: \n";
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        for (Map.Entry<String, Object> entry : jobDataMap.entrySet()) {
            message += entry.getKey() + " = " + entry.getValue() + "\n";
        }
        Mail.sendMail("SCE notification", message, email, null, null);
    } catch (SchedulerException e) {
        throw new JobExecutionException(e);
    }
}

From source file:com.vuze.plugin.azVPN_Helper.Checker_AirVPN.java

private PortInfo[] scrapePorts(InetAddress bindIP, StringBuffer token)
        throws ClientProtocolException, IOException {
    String bindIPString = bindIP == null ? null : bindIP.getHostAddress();
    HttpGet getPortsPage = new HttpGet(VPN_PORTS_URL);
    RequestConfig requestConfig = RequestConfig.custom().setLocalAddress(bindIP).setConnectTimeout(15000)
            .build();/*  ww w .ja va  2  s  .  c  om*/
    getPortsPage.setConfig(requestConfig);
    getPortsPage.setHeader("User-Agent", USER_AGENT);

    CloseableHttpClient httpClientPortsPage = HttpClients.createDefault();
    CloseableHttpResponse portsPageResponse = httpClientPortsPage.execute(getPortsPage, httpClientContext);

    BufferedReader rd = new BufferedReader(new InputStreamReader(portsPageResponse.getEntity().getContent()));

    PortInfo[] ports = parsePorts(rd, bindIPString, token);

    rd.close();

    return ports;
}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.uplink.UplinkReceiver.java

/**
 * @param relayServers/*  w  ww .  j  a va  2 s.com*/
 *          the relayServers to set
 * @throws UnknownHostException
 *           upon error converting an IP address or host name to an INetAddress
 */
@Required
public final void setConfiguredRelayServers(String relayServers) throws UnknownHostException {
    if ((relayServers == null) || relayServers.trim().isEmpty()) {
        this.configuredRelayServers.clear();
        return;
    }

    if (!relayServers.matches(matcher)) {
        throw new IllegalArgumentException(
                "Configured relayServers string does not comply to regular expression \"" + matcher + "\"");
    }

    String[] splits = relayServers.split("\\s*,\\s*");
    for (String split : splits) {
        String[] fields = split.split(":", 2);

        InetAddress ip = InetAddress.getByName(fields[0].trim());

        RelayServer relayServer = new RelayServer();
        relayServer.setIp(ip);

        if (fields.length == 2) {
            Integer port = Integer.valueOf(fields[1].trim());
            if ((port.intValue() <= 0) || (port.intValue() > 65535)) {
                throw new IllegalArgumentException("Configured port " + port.intValue() + " for IP address "
                        + ip.getHostAddress() + " is outside valid range of [1, 65535]");
            }
            relayServer.setPort(port);
        }

        this.configuredRelayServers.add(relayServer);
    }
}

From source file:com.aptana.webserver.internal.core.builtin.LocalWebServer.java

public LocalWebServer(InetAddress host, int[] portRange, URI documentRoot) {
    super();/*  ww w .  j  a va 2s  . co  m*/
    Assert.isLegal(documentRoot != null, "DocumentRoot should be set"); //$NON-NLS-1$
    setDocumentRoot(documentRoot);
    setName(NAME);
    this.host = host;
    this.port = SocketUtil.findFreePort(host, portRange[0], portRange[1]);
    if (this.port <= 0) {
        this.port = SocketUtil.findFreePort(host); // default to any free port
    }
    try {
        this.hostName = host.getHostAddress();
        setBaseURL(new URL("http", hostName, port, "/")); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (MalformedURLException e) {
        IdeLog.logError(WebServerCorePlugin.getDefault(), e);
    }
}

From source file:edu.vt.middleware.gator.log4j.SocketServer.java

/**
 * Gets first project to which the host possessing the given IP address is a
 * member./*from w  ww.  j av  a 2  s  .  c  om*/
 *
 * @param  addr  IP address.
 *
 * @return  First project to which the client at the given IP address is a
 * member or null if client does not belong to project.
 */
public ProjectConfig getProject(final InetAddress addr) {
    ProjectConfig project = null;
    List<ProjectConfig> projects = configManager.findProjectsByClientName(addr.getHostName());
    if (projects.size() > 0) {
        project = projects.get(0);
    } else {
        projects = configManager.findProjectsByClientName(addr.getHostAddress());
        if (projects.size() > 0) {
            project = projects.get(0);
        }
    }
    return project;
}

From source file:io.github.thred.climatetray.ClimateTrayProxySettings.java

public CloseableHttpClient createHttpClient(String... additionalProxyExcludes) {
    if (proxyType == ProxyType.NONE) {
        return HttpClients.createDefault();
    }/*w  w  w  .j a v a2 s.c  om*/

    if (proxyType == ProxyType.SYSTEM_DEFAULT) {
        return HttpClients.createSystem();
    }

    HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
    HttpClientBuilder builder = HttpClientBuilder.create().setProxy(proxy);

    if (isProxyAuthorizationNeeded()) {
        Credentials credentials = new UsernamePasswordCredentials(getProxyUser(), getProxyPassword());
        AuthScope authScope = new AuthScope(getProxyHost(), getProxyPort());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        credsProvider.setCredentials(authScope, credentials);

        builder.setDefaultCredentialsProvider(credsProvider);
    }

    String excludes = proxyExcludes;

    if (Utils.isBlank(excludes)) {
        excludes = "";
    }

    for (String additionalProxyExclude : additionalProxyExcludes) {
        if (excludes.length() > 0) {
            excludes += ", ";
        }

        excludes += additionalProxyExclude;
    }

    if (!Utils.isBlank(excludes)) {
        WildcardPattern pattern = new WildcardPattern(excludes.split("\\s*,\\s*"));
        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy) {
            @Override
            public HttpRoute determineRoute(HttpHost host, HttpRequest request, HttpContext context)
                    throws HttpException {
                InetAddress address = host.getAddress();

                if (address == null) {
                    try {
                        address = InetAddress.getByName(host.getHostName());
                    } catch (UnknownHostException e) {
                        ClimateTray.LOG.info("Failed to determine address of host \"%s\"", host.getHostName());
                    }
                }

                if (address != null) {
                    String hostAddress = address.getHostAddress();

                    if (pattern.matches(hostAddress)) {
                        return new HttpRoute(host);
                    }
                }

                String hostName = host.getHostName();

                if (pattern.matches(hostName)) {
                    return new HttpRoute(host);
                }

                return super.determineRoute(host, request, context);
            }
        };

        builder.setRoutePlanner(routePlanner);
    }

    return builder.build();
}