List of usage examples for org.apache.commons.net.util SubnetUtils SubnetUtils
public SubnetUtils(String address, String mask)
From source file:com.eislab.af.translator.Translator_hub_i.java
private static String findOutgoingIpForGivenAdress(String remoteIP) { if (System.getProperty("os.name").contains("Windows")) { final String COMMAND = "route print -4"; List<RouteInfo> routes = new ArrayList<>(); try {/*from ww w . j a v a 2 s. c o m*/ Process exec = Runtime.getRuntime().exec(COMMAND); BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream())); System.out.println(System.getProperty("os.name")); String line; /* examples: 0.0.0.0 0.0.0.0 10.172.180.1 10.172.180.36 20 0.0.0.0 0.0.0.0 10.187.20.1 10.187.20.225 25 10.172.180.0 255.255.255.0 On-link 10.172.180.36 276 10.172.180.36 255.255.255.255 On-link 10.172.180.36 276 */ Pattern p = Pattern.compile( "^\\s*(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+\\S+?\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+(\\d+)\\s*$"); while ((line = reader.readLine()) != null) { Matcher match = p.matcher(line); if (match.matches()) { String network = match.group(1); String mask = match.group(2); String address = match.group(3); short maskLength = 0; boolean networkMatch = network.contentEquals("0.0.0.0"); if (!networkMatch) { SubnetUtils subnet = new SubnetUtils(network, mask); SubnetUtils.SubnetInfo info = subnet.getInfo(); networkMatch = info.isInRange(remoteIP); maskLength = Short.valueOf(info.getCidrSignature().split("/")[1]); } if (networkMatch) { short metric = Short.valueOf(match.group(4)); routes.add(new RouteInfo(address, (short) 0, maskLength, metric)); } } } Collections.sort(routes); for (RouteInfo route : routes) { } if (!routes.isEmpty()) return routes.get(0).source; } catch (Exception ex) { ex.printStackTrace(); } } else if (System.getProperty("os.name").contains("Linux")) { 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})+) //final String COMMAND = "/sbin/ifconfig"; final String COMMAND = "ip route get " + remoteIP; Process exec = Runtime.getRuntime().exec(COMMAND); BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream())); System.out.println(System.getProperty("os.name")); String line; /* examples: * 10.10.2.130 via 10.0.2.2 dev eth0 src 10.0.2.255 */ Pattern p = Pattern.compile("^.*via.*\\s+dev\\s+.*\\s+src\\s((?:[0-9|\\.]{1,3})+)"); while ((line = reader.readLine()) != null) { Matcher match = p.matcher(line); if (match.matches()) { String address = match.group(1); 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(); } } return null; }
From source file:com.vmware.photon.controller.deployer.dcp.workflow.CreateManagementVmWorkflowService.java
/** * Creates the template for cloud init's user-data file that is later on used by {@link CreateIsoTaskService}. * * @param currentState/*from w ww .j a va 2 s . c o m*/ * @param hostState Supplies the {@link HostService.State} object. * @return * @throws IOException */ private CreateIsoTaskService.FileTemplate createCloudInitUserDataTemplate(State currentState, HostService.State hostState) { CreateIsoTaskService.FileTemplate template = new CreateIsoTaskService.FileTemplate(); template.parameters = new HashMap(); DeployerContext deployerContext = HostUtils.getDeployerContext(this); template.filePath = Paths.get(deployerContext.getScriptDirectory(), "user-data.template").toString(); String gateway = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_GATEWAY); template.parameters.put("$GATEWAY", gateway); String ip = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP); String netMask = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_NETMASK); template.parameters.put("$ADDRESS", new SubnetUtils(ip, netMask).getInfo().getCidrSignature()); String dnsList = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_DNS_SERVER); StringBuilder dnsServerBuilder = new StringBuilder(); if (!Strings.isNullOrEmpty(dnsList)) { for (String dnsServer : dnsList.split(",")) { dnsServerBuilder.append("DNS="); dnsServerBuilder.append(dnsServer); dnsServerBuilder.append("\n"); } } template.parameters.put("$DNS", dnsServerBuilder.toString()); template.parameters.put("$NTP", currentState.ntpEndpoint); return template; }
From source file:com.vmware.photon.controller.deployer.xenon.task.CreateDhcpVmTaskService.java
private void processConfigIso(State currentState, VmService.State vmState, HostService.State hostState) throws Throwable { checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_GATEWAY)); checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP)); checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_NETMASK)); checkState(//from w w w . ja va2 s.co m hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_DNS_SERVER)); String gateway = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_GATEWAY); String ipAddress = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP); String netmask = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_NETMASK); String dnsEndpointList = hostState.metadata .get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_DNS_SERVER); if (!Strings.isNullOrEmpty(dnsEndpointList)) { dnsEndpointList = Stream.of(dnsEndpointList.split(",")).map((dnsServer) -> "DNS=" + dnsServer + "\n") .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); } DeployerContext deployerContext = HostUtils.getDeployerContext(this); String scriptDirectory = deployerContext.getScriptDirectory(); String userDataConfigFileContent = new String( Files.readAllBytes(Paths.get(scriptDirectory, "user-data.template")), StandardCharsets.UTF_8) .replace("$GATEWAY", gateway) .replace("$ADDRESS", new SubnetUtils(ipAddress, netmask).getInfo().getCidrSignature()) .replace("$DNS", dnsEndpointList); if (currentState.ntpEndpoint != null) { userDataConfigFileContent = userDataConfigFileContent.replace("$NTP", currentState.ntpEndpoint); } String metadataConfigFileContent = new String( Files.readAllBytes(Paths.get(scriptDirectory, "meta-data.template")), StandardCharsets.UTF_8) .replace("$INSTANCE_ID", vmState.name).replace("$LOCAL_HOSTNAME", vmState.name); Path vmConfigDirectoryPath = Files.createTempDirectory("iso-" + currentState.vmId).toAbsolutePath(); Path userDataConfigFilePath = vmConfigDirectoryPath.resolve("user-data.yml"); Files.write(userDataConfigFilePath, userDataConfigFileContent.getBytes(StandardCharsets.UTF_8)); Path metadataConfigFilePath = vmConfigDirectoryPath.resolve("meta-data.yml"); Files.write(metadataConfigFilePath, metadataConfigFileContent.getBytes(StandardCharsets.UTF_8)); Path isoFilePath = vmConfigDirectoryPath.resolve("config.iso"); List<String> command = new ArrayList<>(); command.add("./" + SCRIPT_NAME); command.add(isoFilePath.toAbsolutePath().toString()); command.add(userDataConfigFilePath.toAbsolutePath().toString()); command.add(metadataConfigFilePath.toAbsolutePath().toString()); command.add(currentState.serviceConfigDirectory); File scriptLogFile = new File(deployerContext.getScriptLogDirectory(), SCRIPT_NAME + "-" + vmState.vmId + "-" + ServiceUtils.getIDFromDocumentSelfLink(currentState.documentSelfLink) + ".log"); ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec()) .directory(deployerContext.getScriptDirectory()) .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build(); ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner); HostUtils.getListeningExecutorService(this).submit(futureTask); Futures.addCallback(futureTask, new FutureCallback<Integer>() { @Override public void onSuccess(@javax.validation.constraints.NotNull Integer result) { try { if (result != 0) { logScriptErrorAndFail(currentState, result, scriptLogFile); } else { State patchState = buildPatch(TaskState.TaskStage.STARTED, TaskState.SubStage.ATTACH_ISO, null); patchState.vmConfigDirectory = vmConfigDirectoryPath.toAbsolutePath().toString(); TaskUtils.sendSelfPatch(CreateDhcpVmTaskService.this, patchState); } } catch (Throwable t) { failTask(t); } } @Override public void onFailure(Throwable throwable) { failTask(throwable); } }); }
From source file:com.vmware.photon.controller.deployer.xenon.task.CreateManagementVmTaskService.java
private void processConfigIso(State currentState, VmService.State vmState, HostService.State hostState) throws Throwable { checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_GATEWAY)); checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP)); checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_NETMASK)); checkState(//from ww w .jav a 2 s. co m hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_DNS_SERVER)); String gateway = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_GATEWAY); String ipAddress = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP); String netmask = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_NETMASK); String dnsEndpointList = hostState.metadata .get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_DNS_SERVER); String allowedServices = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_ALLOWED_SERVICES); if (!Strings.isNullOrEmpty(dnsEndpointList)) { dnsEndpointList = Stream.of(dnsEndpointList.split(",")).map((dnsServer) -> "DNS=" + dnsServer + "\n") .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); } DeployerContext deployerContext = HostUtils.getDeployerContext(this); String scriptDirectory = deployerContext.getScriptDirectory(); String domainName = DOMAIN_NAME; if (currentState.oAuthTenantName != null) { domainName = currentState.oAuthTenantName; } String userDataConfigFileContent = new String( Files.readAllBytes(Paths.get(scriptDirectory, "user-data.template")), StandardCharsets.UTF_8) .replace("$GATEWAY", gateway) .replace("$ADDRESS", new SubnetUtils(ipAddress, netmask).getInfo().getCidrSignature()) .replace("$DOMAIN_NAME", domainName); if (currentState.ntpEndpoint != null) { userDataConfigFileContent = userDataConfigFileContent.replace("$NTP", currentState.ntpEndpoint); } // If auth is enabled and this VM is the lightwave server, then set dns to its own address and add domain name. // If auth is enabled and this VM is not the lightwave server, then set dns to lightwave VM address and add // domain name. // If auth is not enabled, then use the default dns server, don't set domain. if (currentState.isAuthEnabled && vmState.ipAddress.equals(currentState.oAuthServerAddress)) { userDataConfigFileContent = userDataConfigFileContent.replace("$DNS", "DNS=" + vmState.ipAddress) .replace("$DOMAINS", "Domains=" + domainName); } else if (currentState.isAuthEnabled) { userDataConfigFileContent = userDataConfigFileContent .replace("$DNS", "DNS=" + currentState.oAuthServerAddress) .replace("$DOMAINS", "Domains=" + domainName); } else { userDataConfigFileContent = userDataConfigFileContent.replace("$DNS", dnsEndpointList) .replace("\n $DOMAINS", ""); } String metadataConfigFileContent = new String( Files.readAllBytes(Paths.get(scriptDirectory, "meta-data.template")), StandardCharsets.UTF_8) .replace("$INSTANCE_ID", vmState.name).replace("$LOCAL_HOSTNAME", vmState.name); Path vmConfigDirectoryPath = Files.createTempDirectory("iso-" + currentState.vmId).toAbsolutePath(); Path userDataConfigFilePath = vmConfigDirectoryPath.resolve("user-data.yml"); Files.write(userDataConfigFilePath, userDataConfigFileContent.getBytes(StandardCharsets.UTF_8)); Path metadataConfigFilePath = vmConfigDirectoryPath.resolve("meta-data.yml"); Files.write(metadataConfigFilePath, metadataConfigFileContent.getBytes(StandardCharsets.UTF_8)); Path isoFilePath = vmConfigDirectoryPath.resolve("config.iso"); List<String> command = new ArrayList<>(); command.add("./" + SCRIPT_NAME); command.add(isoFilePath.toAbsolutePath().toString()); command.add(userDataConfigFilePath.toAbsolutePath().toString()); command.add(metadataConfigFilePath.toAbsolutePath().toString()); command.add(currentState.serviceConfigDirectory); File scriptLogFile = new File(deployerContext.getScriptLogDirectory(), SCRIPT_NAME + "-" + vmState.vmId + "-" + ServiceUtils.getIDFromDocumentSelfLink(currentState.documentSelfLink) + ".log"); ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec()) .directory(deployerContext.getScriptDirectory()) .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build(); ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner); HostUtils.getListeningExecutorService(this).submit(futureTask); Futures.addCallback(futureTask, new FutureCallback<Integer>() { @Override public void onSuccess(@javax.validation.constraints.NotNull Integer result) { try { if (result != 0) { logScriptErrorAndFail(currentState, result, scriptLogFile); } else { State patchState = buildPatch(TaskState.TaskStage.STARTED, TaskState.SubStage.ATTACH_ISO, null); patchState.vmConfigDirectory = vmConfigDirectoryPath.toAbsolutePath().toString(); TaskUtils.sendSelfPatch(CreateManagementVmTaskService.this, patchState); } } catch (Throwable t) { failTask(t); } } @Override public void onFailure(Throwable throwable) { failTask(throwable); } }); }
From source file:com.vmware.photon.controller.deployer.dcp.task.CreateManagementVmTaskService.java
private void processConfigIso(State currentState, VmService.State vmState, HostService.State hostState) throws Throwable { checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_GATEWAY)); checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP)); checkState(hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_NETMASK)); checkState(/*from w ww . ja va 2 s . co m*/ hostState.metadata.containsKey(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_DNS_SERVER)); String gateway = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_GATEWAY); String ipAddress = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_IP); String netmask = hostState.metadata.get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_NETMASK); String dnsEndpointList = hostState.metadata .get(HostService.State.METADATA_KEY_NAME_MANAGEMENT_NETWORK_DNS_SERVER); if (!Strings.isNullOrEmpty(dnsEndpointList)) { dnsEndpointList = Stream.of(dnsEndpointList.split(",")).map((dnsServer) -> "DNS=" + dnsServer + "\n") .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); } DeployerContext deployerContext = HostUtils.getDeployerContext(this); String scriptDirectory = deployerContext.getScriptDirectory(); String userDataConfigFileContent = new String( Files.readAllBytes(Paths.get(scriptDirectory, "user-data.template")), StandardCharsets.UTF_8) .replace("$GATEWAY", gateway) .replace("$ADDRESS", new SubnetUtils(ipAddress, netmask).getInfo().getCidrSignature()) .replace("$DNS", dnsEndpointList); if (currentState.ntpEndpoint != null) { userDataConfigFileContent = userDataConfigFileContent.replace("$NTP", currentState.ntpEndpoint); } String metadataConfigFileContent = new String( Files.readAllBytes(Paths.get(scriptDirectory, "meta-data.template")), StandardCharsets.UTF_8) .replace("$INSTANCE_ID", vmState.name).replace("$LOCAL_HOSTNAME", vmState.name); Path vmConfigDirectoryPath = Files.createTempDirectory("iso-" + currentState.vmId).toAbsolutePath(); Path userDataConfigFilePath = vmConfigDirectoryPath.resolve("user-data.yml"); Files.write(userDataConfigFilePath, userDataConfigFileContent.getBytes(StandardCharsets.UTF_8)); Path metadataConfigFilePath = vmConfigDirectoryPath.resolve("meta-data.yml"); Files.write(metadataConfigFilePath, metadataConfigFileContent.getBytes(StandardCharsets.UTF_8)); Path isoFilePath = vmConfigDirectoryPath.resolve("config.iso"); List<String> command = new ArrayList<>(); command.add("./" + SCRIPT_NAME); command.add(isoFilePath.toAbsolutePath().toString()); command.add(userDataConfigFilePath.toAbsolutePath().toString()); command.add(metadataConfigFilePath.toAbsolutePath().toString()); command.add(currentState.serviceConfigDirectory); File scriptLogFile = new File(deployerContext.getScriptLogDirectory(), SCRIPT_NAME + "-" + vmState.vmId + "-" + ServiceUtils.getIDFromDocumentSelfLink(currentState.documentSelfLink) + ".log"); ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec()) .directory(deployerContext.getScriptDirectory()) .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build(); ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner); HostUtils.getListeningExecutorService(this).submit(futureTask); Futures.addCallback(futureTask, new FutureCallback<Integer>() { @Override public void onSuccess(@javax.validation.constraints.NotNull Integer result) { try { if (result != 0) { logScriptErrorAndFail(currentState, result, scriptLogFile); } else { State patchState = buildPatch(TaskState.TaskStage.STARTED, TaskState.SubStage.ATTACH_ISO, null); patchState.vmConfigDirectory = vmConfigDirectoryPath.toAbsolutePath().toString(); TaskUtils.sendSelfPatch(CreateManagementVmTaskService.this, patchState); } } catch (Throwable t) { failTask(t); } } @Override public void onFailure(Throwable throwable) { failTask(throwable); } }); }
From source file:org.apache.sling.discovery.base.connectors.ping.wl.SubnetWhitelistEntry.java
public SubnetWhitelistEntry(String ip, String subnetMask) { subnetInfo = new SubnetUtils(ip, subnetMask).getInfo(); }
From source file:org.cloudsimulator.controller.LocalNetworkController.java
public LocalNetworkController(final LocalNetwork localNetwork) { super();/*from w ww .j a v a 2s .com*/ SubnetUtils subNetUtils = new SubnetUtils(localNetwork.getHasIPAddress(), localNetwork.getHasSubNetworkMask()); SubnetInfo subNetInfo = subNetUtils.getInfo(); this.allAddresses = subNetInfo.getAllAddresses(); this.addressCount = subNetInfo.getAddressCount(); this.localNetwork = localNetwork; }
From source file:org.csstudio.domain.common.net.GatewayUtil.java
public static List<SubnetUtils> getControlSubnets() { final ArrayList<SubnetUtils> controlSubnetsList = new ArrayList<SubnetUtils>(); final List<String> controlSubnets = ControlSubnetPreference.getControlSubnets(); for (final String string : controlSubnets) { final String[] split = string.split("/"); if (split.length == 2) { controlSubnetsList.add(new SubnetUtils(split[0], split[1])); }//w w w . j a v a 2 s . c o m } return controlSubnetsList; }
From source file:org.hkfree.topoagent.module.protocol.NetBIOSScheduleCrate.java
@Override public void execute(final JobExecutionContext jec) throws JobExecutionException, ConcurrentModificationException { Core core = (Core) jec.getJobDetail().getJobDataMap().get("core"); Probe probe = (Probe) jec.getJobDetail().getJobDataMap().get("probe"); byte[] mask = core.getNetworkManager().getActiveDeviceNetmaskAsByte(); SubnetUtils su = new SubnetUtils(core.getNetworkManager().getActiveDeviceIPasString(), FormatUtils.ip(mask));/*w w w .j a v a 2s. co m*/ SubnetInfo info = su.getInfo(); for (String ip : info.getAllAddresses()) { ((NetBIOSProbeService) probe.getProbeService()).GetNetBIOSName(ip); } }
From source file:org.opendaylight.opendove.odmc.OpenDoveSubnet.java
public boolean containsAddress(String ip) { try {// www. j a va 2s .c o m SubnetUtils util = new SubnetUtils(subnet, mask); SubnetInfo info = util.getInfo(); return info.isInRange(ip); } catch (Exception e) { return false; } }