List of usage examples for java.net NetworkInterface getInetAddresses
public Enumeration<InetAddress> getInetAddresses()
From source file:com.sslexplorer.server.Main.java
private void displaySystemInfo() throws SocketException { ///* w ww . j av a 2s . c om*/ if (useDevConfig) { log.warn("Development environment enabled. Do not use this on a production server."); } if (log.isInfoEnabled()) { log.info("Version is " + ContextHolder.getContext().getVersion()); log.info("Java version is " + SystemProperties.get("java.version")); log.info("Server is installed on " + hostname + "/" + hostAddress); log.info("Configuration: " + CONF_DIR.getAbsolutePath()); } if (SystemProperties.get("java.vm.name", "").indexOf("GNU") > -1 || SystemProperties.get("java.vm.name", "").indexOf("libgcj") > -1) { System.out.println("********** WARNING **********"); System.out.println("The system has detected that the Java runtime is GNU/GCJ"); System.out.println("SSL-Explorer does not work correctly with this Java runtime"); System.out.println("you should reconfigure with a different runtime"); System.out.println("*****************************"); log.warn("********** WARNING **********"); log.warn("The system has detected that the Java runtime is GNU/GCJ"); log.warn("SSL-Explorer may not work correctly with this Java runtime"); log.warn("you should reconfigure with a different runtime"); log.warn("*****************************"); } Enumeration e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface netface = (NetworkInterface) e.nextElement(); if (log.isInfoEnabled()) log.info("Net interface: " + netface.getName()); Enumeration e2 = netface.getInetAddresses(); while (e2.hasMoreElements()) { InetAddress ip = (InetAddress) e2.nextElement(); if (log.isInfoEnabled()) log.info("IP address: " + ip.toString()); } } if (log.isInfoEnabled()) log.info("System properties follow:"); Properties sysProps = System.getProperties(); for (Iterator i = sysProps.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); int idx = 0; String val = (String) entry.getValue(); while (true) { if (entry.getKey().equals("java.class.path")) { StringTokenizer t = new StringTokenizer(entry.getValue().toString(), SystemProperties.get("path.separator", ",")); while (t.hasMoreTokens()) { String s = t.nextToken(); if (log.isInfoEnabled()) log.info("java.class.path=" + s); } break; } else { if ((val.length() - idx) > 256) { if (log.isInfoEnabled()) log.info(" " + entry.getKey() + "=" + val.substring(idx, idx + 256)); idx += 256; } else { if (log.isInfoEnabled()) log.info(" " + entry.getKey() + "=" + val.substring(idx)); break; } } } } }
From source file:org.uguess.android.sysinfo.SiragonManager.java
static String getNetAddressInfo() { try {/* w ww .jav a 2s. c o m*/ StringBuffer sb = new StringBuffer(); for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { String addr = inetAddress.getHostAddress(); if (!TextUtils.isEmpty(addr)) { if (sb.length() == 0) { sb.append(addr); } else { sb.append(", ").append(addr); //$NON-NLS-1$ } } } } } String netAddress = sb.toString(); if (!TextUtils.isEmpty(netAddress)) { return netAddress; } } catch (SocketException e) { Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e); } return null; }
From source file:org.pentaho.di.core.Const.java
/** * Determins the IP address of the machine Kettle is running on. * * @return The IP address/*www . j ava2 s.co m*/ */ public static final String getIPAddress() throws Exception { Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces(); while (enumInterfaces.hasMoreElements()) { NetworkInterface nwi = enumInterfaces.nextElement(); Enumeration<InetAddress> ip = nwi.getInetAddresses(); while (ip.hasMoreElements()) { InetAddress in = ip.nextElement(); if (!in.isLoopbackAddress() && in.toString().indexOf(":") < 0) { return in.getHostAddress(); } } } return "127.0.0.1"; }
From source file:org.pentaho.di.core.Const.java
/** * Determine the hostname of the machine Kettle is running on * * @return The hostname/*from w w w .j a v a 2 s. co m*/ */ public static final String getHostname() { if (cachedHostname != null) { return cachedHostname; } // In case we don't want to leave anything to doubt... // String systemHostname = EnvUtil.getSystemProperty(KETTLE_SYSTEM_HOSTNAME); if (!isEmpty(systemHostname)) { cachedHostname = systemHostname; return systemHostname; } String lastHostname = "localhost"; try { Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface nwi = en.nextElement(); Enumeration<InetAddress> ip = nwi.getInetAddresses(); while (ip.hasMoreElements()) { InetAddress in = ip.nextElement(); lastHostname = in.getHostName(); // System.out.println(" ip address bound : "+in.getHostAddress()); // System.out.println(" hostname : "+in.getHostName()); // System.out.println(" Cann.hostname : "+in.getCanonicalHostName()); // System.out.println(" ip string : "+in.toString()); if (!lastHostname.equalsIgnoreCase("localhost") && !(lastHostname.indexOf(':') >= 0)) { break; } } } } catch (SocketException e) { // Eat exception, just return what you have } cachedHostname = lastHostname; return lastHostname; }
From source file:org.pentaho.di.core.Const.java
/** * Get the primary IP address tied to a network interface (excluding loop-back etc) * * @param networkInterfaceName//from ww w . j av a 2 s . com * the name of the network interface to interrogate * @return null if the network interface or address wasn't found. * * @throws SocketException * in case of a security or network error */ public static final String getIPAddress(String networkInterfaceName) throws SocketException { NetworkInterface networkInterface = NetworkInterface.getByName(networkInterfaceName); Enumeration<InetAddress> ipAddresses = networkInterface.getInetAddresses(); while (ipAddresses.hasMoreElements()) { InetAddress inetAddress = ipAddresses.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress.toString().indexOf(":") < 0) { String hostname = inetAddress.getHostAddress(); return hostname; } } return null; }
From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java
@Override public void initScheduler() throws ProvisioningException { if (this.cfgMgr.getCfg().getProvisioning() == null || this.cfgMgr.getCfg().getProvisioning().getScheduler() == null) { logger.warn("Scheduler not defined"); return;//from w w w.j a v a 2 s. c om } SchedulingType sct = this.cfgMgr.getCfg().getProvisioning().getScheduler(); Properties scheduleProps = new Properties(); scheduleProps.setProperty("org.quartz.scheduler.instanceName", sct.getInstanceLabel()); String instanceLabel = null; try { Enumeration<NetworkInterface> enumer = NetworkInterface.getNetworkInterfaces(); while (enumer.hasMoreElements()) { NetworkInterface ni = enumer.nextElement(); Enumeration<InetAddress> enumeri = ni.getInetAddresses(); while (enumeri.hasMoreElements()) { InetAddress addr = enumeri.nextElement(); if (addr.getHostAddress().startsWith(sct.getInstanceIPMask())) { instanceLabel = addr.getHostAddress(); } } } } catch (SocketException e) { throw new ProvisioningException("Could not read network addresses", e); } if (instanceLabel == null) { logger.warn("No IP starts with '" + sct.getInstanceIPMask() + "'"); instanceLabel = "AUTO"; } scheduleProps.setProperty("org.quartz.scheduler.instanceId", instanceLabel); scheduleProps.setProperty("org.quartz.threadPool.threadCount", Integer.toString(sct.getThreadCount())); if (sct.isUseDB()) { scheduleProps.setProperty("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX"); scheduleProps.setProperty("org.quartz.jobStore.driverDelegateClass", sct.getScheduleDB().getDelegateClassName()); scheduleProps.setProperty("org.quartz.jobStore.dataSource", "scheduleDB"); scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.driver", sct.getScheduleDB().getDriver()); scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.URL", sct.getScheduleDB().getUrl()); scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.user", sct.getScheduleDB().getUser()); scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.password", sct.getScheduleDB().getPassword()); scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.maxConnections", Integer.toString(sct.getScheduleDB().getMaxConnections())); scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.validationQuery", sct.getScheduleDB().getValidationQuery()); scheduleProps.setProperty("org.quartz.jobStore.useProperties", "true"); scheduleProps.setProperty("org.quartz.jobStore.isClustered", "true"); } else { scheduleProps.setProperty("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore"); } try { /*String classpath = System.getProperty("java.class.path"); String[] classpathEntries = classpath.split(File.pathSeparator); for (String cp : classpathEntries) { System.out.println(cp); }*/ PrintStream out = new PrintStream(new FileOutputStream( System.getProperty(OpenUnisonConstants.UNISON_CONFIG_QUARTZDIR) + "/quartz.properties")); scheduleProps.store(out, "Unison internal scheduler properties"); out.flush(); out.close(); } catch (IOException e) { throw new ProvisioningException("Could not write to quartz.properties", e); } try { this.scheduler = StdSchedulerFactory.getDefaultScheduler(); this.scheduler.start(); this.cfgMgr.addThread(new StopScheduler(this.scheduler)); HashSet<String> jobKeys = new HashSet<String>(); for (JobType jobType : sct.getJob()) { jobKeys.add(jobType.getName() + "-" + jobType.getGroup()); JobKey jk = new JobKey(jobType.getName(), jobType.getGroup()); JobDetail jd = this.scheduler.getJobDetail(jk); if (jd == null) { logger.info("Adding new job '" + jobType.getName() + "' / '" + jobType.getGroup() + "'"); try { addJob(jobType, jk); } catch (ClassNotFoundException e) { throw new ProvisioningException("Could not initialize job", e); } } else { //check to see if we need to modify StringBuffer cron = new StringBuffer(); cron.append(jobType.getCronSchedule().getSeconds()).append(' ') .append(jobType.getCronSchedule().getMinutes()).append(' ') .append(jobType.getCronSchedule().getHours()).append(' ') .append(jobType.getCronSchedule().getDayOfMonth()).append(' ') .append(jobType.getCronSchedule().getMonth()).append(' ') .append(jobType.getCronSchedule().getDayOfWeek()).append(' ') .append(jobType.getCronSchedule().getYear()); Properties configProps = new Properties(); for (ParamType pt : jobType.getParam()) { configProps.setProperty(pt.getName(), pt.getValue()); } Properties jobProps = new Properties(); for (String key : jd.getJobDataMap().getKeys()) { jobProps.setProperty(key, (String) jd.getJobDataMap().getString(key)); } List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jd.getKey()); CronTrigger trigger = (CronTrigger) triggers.get(0); if (!jobType.getClassName().equals(jd.getJobClass().getName())) { logger.info("Reloading job '" + jobType.getName() + "' / '" + jobType.getGroup() + "' - change in class name"); reloadJob(jobType, jd); } else if (!cron.toString().equalsIgnoreCase(trigger.getCronExpression())) { logger.info("Reloading job '" + jobType.getName() + "' / '" + jobType.getGroup() + "' - change in schedule"); reloadJob(jobType, jd); } else if (!configProps.equals(jobProps)) { logger.info("Reloading job '" + jobType.getName() + "' / '" + jobType.getGroup() + "' - change in properties"); reloadJob(jobType, jd); } } } for (String groupName : scheduler.getJobGroupNames()) { for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) { String jobName = jobKey.getName(); String jobGroup = jobKey.getGroup(); //get job's trigger List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey); if (!jobKeys.contains(jobName + "-" + jobGroup)) { logger.info("Removing jab '" + jobName + "' / '" + jobGroup + "'"); scheduler.deleteJob(jobKey); } } } } catch (SchedulerException e) { throw new ProvisioningException("Could not initialize scheduler", e); } catch (ClassNotFoundException e) { throw new ProvisioningException("Could not initialize scheduler", e); } }
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); }//from w ww. j av a 2 s.co 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:configuration.Util.java
/** * Code from : http://stackoverflow.com/questions/8083479/java-getting-my-ip-address * * @return// w w w . j a va 2 s . com */ public String ip() { String ip; try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface iface = interfaces.nextElement(); // filters out 127.0.0.1 and inactive interfaces if (iface.isLoopback() || !iface.isUp()) continue; Enumeration<InetAddress> addresses = iface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); ip = addr.getHostAddress(); return ip; //System.out.println(iface.getDisplayName() + " " + ip); } } } catch (Exception e) { System.out.println("Ip Failed!"); System.out.println(e); return ""; } return ""; }
From source file:org.smilec.smile.student.CourseList.java
private String get_IP() { try {// w w w .j a v a 2s .com Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface ni = e.nextElement(); Enumeration<InetAddress> ips = ni.getInetAddresses(); while (ips.hasMoreElements()) { String ipa = ips.nextElement().toString(); if (ipa.startsWith("/")) ipa = ipa.substring(1); if (ipa.indexOf(':') >= 0) { // IPv6. Ignore continue; } if (ipa.equals("127.0.0.1")) { continue; // loopback MY_IP. Not meaningful for out // purpose } Log.d(APP_TAG, ipa); return ipa; } } } catch (SocketException e) { e.printStackTrace(); } return null; }