List of usage examples for java.net InetAddress getHostAddress
public String getHostAddress()
From source file:com.digitalpebble.stormcrawler.util.URLPartitioner.java
/** * Returns the host, domain, IP of a URL so that it can be partitioned for * politeness/*from w w w . j av a2 s . c o m*/ **/ public String getPartition(String url, Metadata metadata) { String partitionKey = null; String host = ""; // IP in metadata? if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_IP)) { String ip_provided = metadata.getFirstValue("ip"); if (StringUtils.isNotBlank(ip_provided)) { partitionKey = ip_provided; } } if (partitionKey == null) { URL u; try { u = new URL(url); host = u.getHost(); } catch (MalformedURLException e1) { LOG.warn("Invalid URL: {}", url); return null; } } // partition by hostname if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_HOST)) partitionKey = host; // partition by domain : needs fixing else if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_DOMAIN)) { partitionKey = PaidLevelDomain.getPLD(host); } // partition by IP if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_IP) && partitionKey == null) { try { long start = System.currentTimeMillis(); final InetAddress addr = InetAddress.getByName(host); partitionKey = addr.getHostAddress(); long end = System.currentTimeMillis(); LOG.debug("Resolved IP {} in {} msec for : {}", partitionKey, end - start, url); } catch (final Exception e) { LOG.warn("Unable to resolve IP for: {}", host); return null; } } LOG.debug("Partition Key for: {} > {}", url, partitionKey); return partitionKey; }
From source file:org.qi4j.library.shiro.StrictX509Test.java
@Override protected void configureJetty(Server jetty) throws Exception { InetAddress lo = InetAddress.getLocalHost(); int sslPort = findFreePortOnIfaceWithPreference(lo, 8443); httpHost = new HttpHost(lo.getHostAddress(), sslPort, "https"); SslSelectChannelConnector sslConnector = new SslSelectChannelConnector(); sslConnector.setPort(httpHost.getPort()); sslConnector.setNeedClientAuth(true); sslConnector.setSslContext(X509FixturesData.serverSSLContext()); sslConnector.setAllowRenegotiate(false); jetty.addConnector(sslConnector);//w w w . j a v a2 s .co m }
From source file:com.skp.experiment.cf.als.hadoop.SolveImplicitFeedbackMultithreadedMapper.java
/** create file lock per each datanode to prevent too many map task simultaneously * runs on same datanode *///from w w w .jav a2 s . c om private void checkLock(Context ctx, int lockNums) throws InterruptedException, IOException { InetAddress thisIp = InetAddress.getLocalHost(); String hostIp = thisIp.getHostAddress(); // busy wait Configuration conf = ctx.getConfiguration(); long totalSleep = 0; boolean haveLock = false; FileSystem fs = FileSystem.get(conf); while (haveLock == false) { for (int i = 0; i < lockNums; i++) { Path checkPath = new Path(lockPath, hostIp + "_" + i); if (fs.exists(checkPath) == false) { haveLock = true; currentLockPath = checkPath; BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fs.create(currentLockPath))); br.write(ctx.getTaskAttemptID().toString()); break; } } if (haveLock == false) { Random random = new Random(); int diff = 1000 + random.nextInt(1000) % 1000; totalSleep += diff + sleepPeriod; ctx.setStatus("sleeping: " + String.valueOf(totalSleep)); Thread.sleep(sleepPeriod + diff); } } }
From source file:com.eislab.af.translator.Translator_hub_i.java
private static String findOutgoingIpV6GivenAddress(String remoteIP) throws Exception { System.out.println("remoteIP: " + remoteIP); if (remoteIP.startsWith("[")) { remoteIP = remoteIP.substring(1, remoteIP.length() - 1); System.out.println("remoteIP: " + remoteIP); }/* w w w . j a va2 s . c o m*/ if (System.getProperty("os.name").contains("Windows")) { NetworkInterface networkInterface; //if ipv6 then find the ipaddress of the network interface String line; short foundIfIndex = 0; final String COMMAND = "route print -6"; List<RouteInfo> routes = new ArrayList<>(); try { Process exec = Runtime.getRuntime().exec(COMMAND); BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream())); //\s+addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$ Pattern p = Pattern.compile("^\\s*(\\d+)\\s+(\\d+)\\s+(.*)\\s+(.*)$"); while ((line = reader.readLine()) != null) { //do not check persistent routes. Only active routes if (line.startsWith("Persistent Routes")) { break; } Matcher match = p.matcher(line); if (match.matches()) { // System.out.println("line match: " + line); String network = match.group(3).split("/")[0]; //String mask = match.group(2); //String address = match.group(3); short maskLength = Short.valueOf(match.group(3).split("/")[1].trim()); boolean networkMatch = ipv6InRange(network, maskLength, remoteIP); if (networkMatch) { short interfaceIndex = Short.valueOf(match.group(1)); short metric = Short.valueOf(match.group(2)); routes.add(new RouteInfo("", interfaceIndex, maskLength, metric)); System.out.println("added route: " + line); } } } Collections.sort(routes); for (RouteInfo route : routes) { } if (!routes.isEmpty()) { foundIfIndex = routes.get(0).ifIndex; //based o nthe network interface index get the ip address networkInterface = NetworkInterface.getByIndex(foundIfIndex); Enumeration<InetAddress> test = networkInterface.getInetAddresses(); while (test.hasMoreElements()) { InetAddress inetaddress = test.nextElement(); if (inetaddress.isLinkLocalAddress()) { continue; } else { if (inetaddress instanceof Inet6Address) { System.out.println("interface host address: " + inetaddress.getHostAddress()); return "[" + inetaddress.getHostAddress() + "]"; } else continue; } } } else { //routes is Empty! System.out.println("No routable interface for remote IP"); throw new Exception("No routable interface for remote IP"); } } catch (Exception ex) { ex.printStackTrace(); throw ex; } } else { List<RouteInfo> routes = new ArrayList<>(); try { //ipv6 ^(.+)/(\d+)\s+(.+)\s(\d+)\s+(\d+)\s+(\d)\s+(.+)$ //ipv4 ^\s+inet\s\addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$ //linux route get command parsing: ipv4^.*via.*\s+dev\s+.*\s+src\s((?:[0-9\.]{1,3})+) //linux route get comand parsing: ipv6 ^.*\sfrom\s::\svia.*\sdev\s.*\ssrc\s((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+) //new one ^.*\s+from\s+::\s+via.*\s+dev\s+.*\ssrc\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)\s+metric\s+\d+ //final String COMMAND = "/sbin/ifconfig"; final String COMMAND = "ip route get " + remoteIP; System.out.println("command = " + COMMAND); Process exec = Runtime.getRuntime().exec(COMMAND); BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream())); System.out.println(System.getProperty("os.name")); String line; /* examples: * fdfd:55::98ac from :: via fdfd:55::98ac dev usb0 src fdfd:55::80fe metric 0 */ Pattern p = Pattern.compile( "^.*\\s+from\\s+::\\s+via.*\\sdev\\s+.*\\s+src\\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)\\s+metric\\s+\\d+.*"); //String test = "fdfd:55::80ff from :: via fdfd:55::80ff dev usb0 src fdfd:55::80fe metric 0"; while ((line = reader.readLine()) != null) { System.out.println("result of command = " + line); Matcher match = p.matcher(line); if (match.matches()) { String address = match.group(1); System.out.println("match found. address = " + address); routes.add(new RouteInfo(address, (short) 0, (short) 0, (short) 0));//metric is always 0, because we do not extract it from the ifconfig command. } } Collections.sort(routes); if (!routes.isEmpty()) return routes.get(0).source; } catch (Exception ex) { ex.printStackTrace(); } //^\s+inet6\s+addr:\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)/(\d{1,3})\s+\Scope:Global$ // NetworkInterface networkInterface; // // //if ipv6 then find the ipaddress of the network interface // String line; // short foundIfIndex = 0; // final String COMMAND = "/sbin/ifconfig"; // List<RouteInfo> routes = new ArrayList<>(); // try { // Process exec = Runtime.getRuntime().exec(COMMAND); // BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream())); // //\s+addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$ // Pattern p = Pattern.compile("^\\s+inet6\\s+addr:\\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)/(\\d{1,3})\\s+\\Scope:Global$"); // while ((line = reader.readLine()) != null) { // //do not check persistent routes. Only active routes // if(line.startsWith("Persistent Routes")) { // break; // } // // Matcher match = p.matcher(line); // if (match.matches()) { // String network = match.group(1).trim(); // short maskLength = Short.valueOf(match.group(2).trim()); // // boolean networkMatch = ipv6InRange(network, maskLength, remoteIP); // // if (networkMatch) { // short interfaceIndex = Short.valueOf(match.group(1)); // short metric = Short.valueOf(match.group(2)); // routes.add(new RouteInfo("", interfaceIndex, maskLength, metric)); // System.out.println("added route: " + line); // } // } // } // Collections.sort(routes); // for (RouteInfo route : routes) { // } // // if (!routes.isEmpty()) { // foundIfIndex = routes.get(0).ifIndex; // // //based o nthe network interface index get the ip address // networkInterface = NetworkInterface.getByIndex(foundIfIndex); // // Enumeration<InetAddress> test = networkInterface.getInetAddresses(); // // while (test.hasMoreElements()) { // InetAddress inetaddress = test.nextElement(); // if (inetaddress.isLinkLocalAddress()) { // continue; // } else { // if (inetaddress instanceof Inet6Address) { // System.out.println("interface host address: " + inetaddress.getHostAddress()); // return "[" + inetaddress.getHostAddress() + "]"; // } else continue; // } // } // } else { //routes is Empty! // System.out.println("No routable interface for remote IP"); // throw new Exception("No routable interface for remote IP"); // } // } catch (Exception ex) { // ex.printStackTrace(); // throw ex; // } } return null; }
From source file:com.zz.cluster4spring.localinfo.DefaultLocalNetworkInfoProvider.java
public String getLocalHostAddress() throws UnknownHostException { InetAddress localHost = InetAddress.getLocalHost(); String result = localHost.getHostAddress(); return result; }
From source file:com.marcosdiez.server.php.service.Network.java
public Network() { names = new LinkedList<String>(); titles = new LinkedList<String>(); adresses = new LinkedList<String>(); try {/*from w w w . j av a 2 s. co m*/ List<NetworkInterface> list = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface iface : list) { List<InetAddress> addresses = Collections.list(iface.getInetAddresses()); for (InetAddress address : addresses) { if (!address.isLoopbackAddress()) { String host = address.getHostAddress().toUpperCase(); if (InetAddressUtils.isIPv4Address(host)) { names.add(iface.getName()); titles.add(host + "(" + iface.getDisplayName() + ")"); adresses.add(host); } } } } for (NetworkInterface iface : list) { List<InetAddress> addresses = Collections.list(iface.getInetAddresses()); for (InetAddress address : addresses) { if (address.isLoopbackAddress()) { String host = address.getHostAddress().toUpperCase(); if (InetAddressUtils.isIPv4Address(host)) { names.add(iface.getName()); titles.add(host + "(" + iface.getDisplayName() + ")"); adresses.add(host); } } } } } catch (Exception ex) { } names.add("all"); adresses.add("0.0.0.0"); titles.add("0.0.0.0 (all)"); }
From source file:com.adito.agent.client.DirectTCPSocketFactory.java
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { try {// ww w .ja v a 2 s.c o m return new LocalForwardingChannelSocket(agent, address.getHostAddress(), port); } catch (ChannelOpenException e) { rethrow(e); } return null; }
From source file:org.ebayopensource.scc.track.TrackerClient.java
public String getIp() { InetAddress ia = getInetAddress(); return ia != null ? ia.getHostAddress() : Tracker.UNKNOWN; }
From source file:com.bleum.canton.loadpage.LoadPage.java
private void logLocalIp(PrintWriter writer) { InetAddress addr; try {//from w w w .ja v a 2s . c o m addr = InetAddress.getLocalHost(); String ip = addr.getHostAddress(); LOGGER.info("IP address of localhost is: " + ip); ip = getWebIp("http://checkip.amazonaws.com/"); LOGGER.info("External ip address of " + ip); writer.print(ip + CSV_SEPERATOR); } catch (UnknownHostException e) { // TODO Auto-generated catch block } }
From source file:com.intellij.plugins.firstspirit.languagesupport.FirstSpiritClassPathHack.java
public void addFirstSpiritClientJar(UrlClassLoader classLoader, HttpScheme schema, String serverName, int port, String firstSpiritUserName, String firstSpiritUserPassword) throws Exception { System.out.println("starting to download fs-client.jar"); String resolvalbleAddress = null; // asking DNS for IP Address, if some error occur choose the given value from user try {// ww w .j a va 2 s. com InetAddress address = InetAddress.getByName(serverName); resolvalbleAddress = address.getHostAddress(); System.out.println("Resolved address: " + resolvalbleAddress); } catch (Exception e) { System.err.println("DNS cannot resolve address, using your given value: " + serverName); resolvalbleAddress = serverName; } String uri = schema + "://" + resolvalbleAddress + ":" + port + "/clientjar/fs-client.jar"; String versionUri = schema + "://" + resolvalbleAddress + ":" + port + "/version.txt"; String tempDirectory = System.getProperty("java.io.tmpdir"); System.out.println(uri); System.out.println(versionUri); HttpClient client = new HttpClient(); HttpMethod getVersion = new GetMethod(versionUri); client.executeMethod(getVersion); String currentServerVersionString = getVersion.getResponseBodyAsString(); System.out .println("FirstSpirit server you want to connect to is at version: " + currentServerVersionString); File fsClientJar = new File(tempDirectory, "fs-client-" + currentServerVersionString + ".jar"); if (!fsClientJar.exists()) { // get an authentication cookie from FirstSpirit HttpMethod post = new PostMethod(uri); post.setQueryString("login.user=" + URLEncoder.encode(firstSpiritUserName, "UTF-8") + "&login.password=" + URLEncoder.encode(firstSpiritUserPassword, "UTF-8") + "&login=webnonsso"); client.executeMethod(post); String setCookieJsession = post.getResponseHeader("Set-Cookie").getValue(); // download the fs-client.jar by using the authentication cookie HttpMethod get = new GetMethod(uri); get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); get.setRequestHeader("Cookie", setCookieJsession); client.executeMethod(get); InputStream inputStream = get.getResponseBodyAsStream(); FileOutputStream outputStream = new FileOutputStream(fsClientJar); outputStream.write(IOUtils.readFully(inputStream, -1, false)); outputStream.close(); System.out.println("tempfile of fs-client.jar created within path: " + fsClientJar); } addFile(classLoader, fsClientJar); }