List of usage examples for java.net NetworkInterface getByInetAddress
public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException
From source file:com.asquareb.kaaval.MachineKey.java
/** * Method to encrypt a string. Accepts the string to be encrypted and the * name of the file to store the key vale which can be used for decryption *///ww w .java2 s.c o m public static String encrypt(String property, String app) throws IOException, KaavalException { InetAddress ip = null; String ipAddress = null; ObjectOutputStream os = null; NetworkInterface macAddress = null; byte[] macId = null; Cipher pbeCipher = null; Random rand = new Random(); rand.nextBytes(salt); try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(password)); ip = InetAddress.getLocalHost(); ipAddress = ip.getHostAddress(); macAddress = NetworkInterface.getByInetAddress(ip); macId = macAddress.getHardwareAddress(); MachineKey mKey = new MachineKey(); mKey.api = ipAddress; mKey.macad = new String(macId); mKey.yek = key; mKey.tlas = salt; mKey.eti = rand.nextInt(1000); os = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(app))); os.writeObject(mKey); os.close(); pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, mKey.eti)); return base64Encode(pbeCipher.doFinal(property.getBytes())); } catch (IOException e) { throw new KaavalException(1, "Error in key file during encryption", e); } catch (Exception e) { throw new KaavalException(2, "Errors during encryption", e); } finally { if (os != null) os.close(); } }
From source file:ws.argo.responder.plugin.repeater.mqtt.MqttRepeaterProbeHandlerPlugin.java
private void initializeProbeSender(Properties properties) throws UnknownHostException, SocketException, TransportConfigException { Transport transport = new MqttSenderTransport(); NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); String macAddr = ni.getHardwareAddress().toString(); String clientId = "MQTT-Repeater-Client-" + macAddr; properties.put("clientId", clientId); transport.initialize(properties, ""); _sender = new ProbeSender(transport); }
From source file:com.adito.tunnels.wizards.forms.TunnelDetailsForm.java
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { if (getResourceName() != null && isCommiting()) { ActionErrors errs = super.validate(mapping, request); AbstractWizardSequence seq = getWizardSequence(request); if (!Util.isNullOrTrimmedBlank(sourceInterface)) { /**/*from w ww .j av a 2 s.co m*/ * For remote tunnels, the listening interface must be a valid * IP address of a network interface on this server */ if (getTunnelType() == TransportType.REMOTE_TUNNEL_ID) { if (!sourceInterface.trim().equals("0.0.0.0") && !sourceInterface.trim().equals("127.0.0.2")) try { InetAddress addr = InetAddress.getByName(sourceInterface); NetworkInterface nif = NetworkInterface.getByInetAddress(addr); if (nif == null) { throw new Exception(); } } catch (Exception e) { errs.add(Globals.ERROR_KEY, new ActionMessage( "tunnelWizard.tunnelDetails.error.invalidRemoteSourceInterface")); } } else { /** * For local tunnels, we do not know what will be a valid IP * address until the client is running so all we can do * is validate that it looks like an IP address */ if (!IPV4AddressValidator.isIpAddressExpressionValid(sourceInterface)) { errs.add(Globals.ERROR_KEY, new ActionMessage("tunnelWizard.tunnelDetails.error.invalidLocalSourceInterface")); } } } try { int port = Integer.valueOf(sourcePort).intValue(); if (port < 0 || port > 65535) { throw new IllegalArgumentException(); } } catch (Exception e) { errs.add(Globals.ERROR_KEY, new BundleActionMessage(seq.getCurrentPageForm().getResourceBundle(), seq.getCurrentPageForm().getResourcePrefix() + ".error.sourcePortNotInteger")); } try { int port = Integer.valueOf(destinationPort).intValue(); if (port < 1 || port > 65535) { throw new IllegalArgumentException(); } } catch (Exception e) { errs.add(Globals.ERROR_KEY, new BundleActionMessage(seq.getCurrentPageForm().getResourceBundle(), seq.getCurrentPageForm().getResourcePrefix() + ".error.destinationPortNotInteger")); } if (destinationHost == null || destinationHost.equals("")) { errs.add(Globals.ERROR_KEY, new BundleActionMessage(seq.getCurrentPageForm().getResourceBundle(), seq.getCurrentPageForm().getResourcePrefix() + ".error.noDestinationHost")); } else { if (!HostnameOrIPAddressWithReplacementsValidator.isValidAsHostOrIp(destinationHost)) { errs.add(Globals.ERROR_KEY, new ActionMessage("tunnelWizard.tunnelDetails.error.invalidHost")); } } if (transport.equals(TransportType.UDP_TUNNEL) && tunnelType == TransportType.REMOTE_TUNNEL_ID) { errs.add(Globals.ERROR_KEY, new BundleActionMessage(seq.getCurrentPageForm().getResourceBundle(), seq.getCurrentPageForm().getResourcePrefix() + ".error.remote.udp")); } return errs; } return null; }
From source file:com.yahoo.gondola.container.Utils.java
/** * Check address is on the server/*from w w w .java 2 s. c o m*/ */ public static boolean isMyAddress(InetAddress address) { // Check if the address is a valid special local or loop back if (address.isAnyLocalAddress() || address.isLoopbackAddress()) { return true; } // Check if the address is defined on any interface try { return NetworkInterface.getByInetAddress(address) != null; } catch (SocketException e) { return false; } }
From source file:org.openhab.binding.globalcache.internal.handler.GlobalCacheHandler.java
@Override public void initialize() { logger.debug("Initializing thing {}", thingID()); try {// w ww. jav a2 s . c o m ifAddress = InetAddress.getByName(ipv4Address); logger.debug("Handler using address {} on network interface {}", ifAddress.getHostAddress(), NetworkInterface.getByInetAddress(ifAddress).getName()); } catch (SocketException e) { logger.error("Handler got Socket exception creating multicast socket: {}", e.getMessage()); markThingOfflineWithError(ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "No suitable network interface"); return; } catch (UnknownHostException e) { logger.error("Handler got UnknownHostException getting local IPv4 network interface: {}", e.getMessage()); markThingOfflineWithError(ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "No suitable network interface"); return; } scheduledFuture = scheduledExecutorService.schedule(commandProcessor, 2, TimeUnit.SECONDS); }
From source file:org.apache.nifi.processors.rt.DeviceRegistryReportingTask.java
private NiFiDevice populateNetworkingInfo(NiFiDevice device) { InetAddress ip;// w w w .j av a 2 s .c o m try { ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); //Check this isn't null if (network == null) { //Hail mary to try and get eth0 getLogger().warn( "Hardcoded getting network interface by ETH0 which could be the incorrect interface but others were null"); network = NetworkInterface.getByName("eth0"); } byte[] mac = network.getHardwareAddress(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : "")); } //Set the values to the device object. device.setDeviceId(sb.toString()); device.setIp(ip.getHostAddress()); String hostname = InetAddress.getLocalHost().getHostName(); logger.error("First attempt at getting hostname: " + hostname); if (!StringUtils.isEmpty(hostname)) { device.setHostname(hostname); } else { //Try the linux approach ... could fail if hostname(1) system command is not available. try { Process process = Runtime.getRuntime().exec("hostname"); InputStream is = process.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); hostname = writer.toString(); if (StringUtils.isEmpty(hostname)) { device.setHostname("UNKNOWN"); } else { device.setHostname(hostname); } } catch (Exception ex) { ex.printStackTrace(); logger.error("Error attempting to resolve hostname", ex); } } } catch (UnknownHostException e) { e.printStackTrace(); logger.error("Unknown host exception getting hostname", e); } catch (SocketException e) { e.printStackTrace(); logger.error("socket exception getting hostname", e); } return device; }
From source file:org.noroomattheinn.visibletesla.App.java
final String getAppID() { String appID = "Unidentified"; try {// w w w . ja v a 2 s. co m InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); if (network != null) { byte[] mac = network.getHardwareAddress(); appID = DigestUtils.sha256Hex(mac); } } catch (UnknownHostException | SocketException e) { logger.warning("Unable to generate an AppID: " + e.getMessage()); } return appID; }
From source file:com.asquareb.kaaval.MachineKey.java
/** * Method to decrypt a string. Accepts the string to be decrypted and the * name of the file which stores the key values *//*from w ww .jav a 2 s .c o m*/ public static String decrypt(String property, String app) throws IOException, KaavalException { SecretKey key = null; ObjectInputStream is = null; MachineKey mKey = null; int eti = 0; Cipher pbeCipher = null; InetAddress ip = InetAddress.getLocalHost(); NetworkInterface macAddress = NetworkInterface.getByInetAddress(ip); byte[] macId = macAddress.getHardwareAddress(); try { is = new ObjectInputStream(new BufferedInputStream(new FileInputStream(app))); mKey = (MachineKey) is.readObject(); key = mKey.yek; salt = mKey.tlas; eti = mKey.eti; String ipa = ip.getHostAddress(); if (!ipa.equals(mKey.api) || !new String(macId).equals(mKey.macad)) throw new KaavalException(5, "Key file is not for this machine"); is.close(); pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, eti)); return new String(pbeCipher.doFinal(base64Decode(property))); } catch (IOException e) { throw new KaavalException(3, "Error in reading key file during decryption", e); } catch (KaavalException e) { throw e; } catch (Exception e) { throw new KaavalException(4, "Error during decryption", e); } finally { if (is != null) is.close(); } }
From source file:com.momathink.common.tools.ToolMonitor.java
/** * MAC? //from www . j a v a2s .c o m * @return : "00 00 00 00 00 00" */ private String getMACAddr() { String mac = ""; try { NetworkInterface netInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); byte[] macAddr = netInterface.getHardwareAddress(); String macByte = ""; // ???? for (byte b : macAddr) { macByte = Integer.toHexString((int) (b & 0xff)); if (macByte.length() == 1) { macByte = "0" + macByte; } mac = mac + " " + macByte; } } catch (Exception e) { } return mac.substring(1); }
From source file:org.cocos2dx.lib.CCUtils.java
public static String getMacAddress() { String mac = ""; Context ctx = Cocos2dxActivity.getContext(); // first, try to get mac from wifi manager if (ctx.checkCallingPermission(permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED) { WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); mac = info.getMacAddress();//from ww w . j av a 2 s . c o m } // if failed, try from network interface api if (TextUtils.isEmpty(mac)) { if (Build.VERSION.SDK_INT >= 9) { try { NetworkInterface ne = NetworkInterface .getByInetAddress(InetAddress.getByName(getLocalIpAddress())); byte[] b = ne.getHardwareAddress(); mac = byte2Hex(b); } catch (Exception e) { e.printStackTrace(); } } } // if failed, use fake if (TextUtils.isEmpty(mac)) { mac = "00:00:00:00:00:00"; } // return return mac; }