List of usage examples for java.net NetworkInterface getByInetAddress
public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException
From source file:com.clustercontrol.repository.util.NodeSearchUtil.java
/** * Generate default IP for node search/create dialog *//* w w w .ja va2 s.c om*/ public static String generateDefaultIp(String def, int hostAddress) { try { // Get IP InetAddress addr = Inet4Address.getLocalHost(); // Get subnet mask length int prefixLength = -1; NetworkInterface ni = NetworkInterface.getByInetAddress(addr); for (InterfaceAddress iaddr : ni.getInterfaceAddresses()) { if (iaddr.getAddress() instanceof Inet4Address) { prefixLength = iaddr.getNetworkPrefixLength(); break; } } if (-1 == prefixLength) { return def; } byte[] ipRaw = addr.getAddress(); // For ipv4 if (4 == ipRaw.length) { int counter = prefixLength; for (int i = 0; i < ipRaw.length; i++) { if (counter < 8) { byte mask = 0x00; for (int j = 0; j < counter; j++) { mask = (byte) (mask >> 1 | 0x80); } ipRaw[i] = (byte) (ipRaw[i] & mask); } counter -= 8; } // Re-format/round up hostAddress if (hostAddress < 0) { hostAddress += Math.pow(2, 32 - prefixLength); } // Add host address part int part = 4; while (hostAddress > 0 && part > 0) { ipRaw[part - 1] += (hostAddress & 0xff); hostAddress >>= 8; } return Inet4Address.getByAddress(ipRaw).getHostAddress(); } // TODO Support ipv6? } catch (UnknownHostException | SocketException e) { m_log.debug(e); } return def; }
From source file:projetohorus.TamanhoHost.java
void TamanhoHost() throws UnknownHostException, SocketException { InetAddress localHost = Inet4Address.getLocalHost(); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost); short x = networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength(); String n = localHost.getHostAddress() + "/" + x; System.out.println(n);/*www . j ava 2 s . co m*/ SubnetUtils utils = new SubnetUtils(n); System.out.println(utils.getInfo()); String first = utils.getInfo().getLowAddress(); String last = utils.getInfo().getHighAddress(); String[] iplast = last.split(Pattern.quote(".")); String[] ipfirst = first.split(Pattern.quote(".")); numfirst = Integer.parseInt(ipfirst[3]); numlast = Integer.parseInt(iplast[3]); }
From source file:org.tinymediamanager.core.License.java
/** * returns the MAC address of this instance * //from w w w . ja v a 2 s . c o m * @return MAC or empty string */ public static String getMac() { try { InetAddress ip = InetAddress.getLocalHost(); if (ip != null) { // we are connected to Internet/router and have an IP NetworkInterface ni = NetworkInterface.getByInetAddress(ip); if (ni == null) { // search for other interfaces Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface network = networkInterfaces.nextElement(); if (!network.isLoopback()) { ni = network; break; } } } String macAddress = formatMac(ni.getHardwareAddress()); if (macAddress != null && !macAddress.isEmpty()) { return macAddress; } } } catch (Exception e) { e.printStackTrace(); LOGGER.warn("Error getting MAC from LocalHost IP - not connected to internet/router?"); } try { for (Enumeration<NetworkInterface> nif = NetworkInterface.getNetworkInterfaces(); nif .hasMoreElements();) { NetworkInterface ni = null; try { ni = nif.nextElement(); String macAddress = formatMac(ni.getHardwareAddress()); if (macAddress != null && !macAddress.isEmpty()) { // get first return macAddress; } } catch (Exception e2) { LOGGER.warn("Error getting MAC of " + ni); } } return UNKNOWN_MAC; } catch (Exception e) { LOGGER.warn("I/O Error on getting network interfaces"); return UNKNOWN_MAC; } }
From source file:de.pawlidi.openaletheia.utils.AletheiaUtils.java
/** * Read java networt mac adress/* w ww. j a v a2s . co m*/ * * @return */ public static String getJavaNetMacAddress() { String javaMacAdress = null; try { InetAddress ip = InetAddress.getLocalHost(); if (ip == null) { return null; } NetworkInterface network = NetworkInterface.getByInetAddress(ip); if (network == null) { return null; } byte[] mac = network.getHardwareAddress(); javaMacAdress = Converter.hexToString(mac); } catch (UnknownHostException e) { // ignore exception } catch (SocketException e) { // ignore exception } return javaMacAdress; }
From source file:projetohorus.DadosColetadosPDF.java
void GerarPDF() throws IOException, DocumentException, EmailException { Document doc = null;//from w w w.j a va2s .c om OutputStream os = null; try { doc = new Document(PageSize.A4, 72, 72, 72, 72); os = new FileOutputStream("tesfinal11.pdf"); PdfWriter.getInstance(doc, os); doc.open(); Image img = Image.getInstance("LogoProject.png"); img.setAlignment(Element.ALIGN_CENTER); doc.add(img); InetAddress localHost = Inet4Address.getLocalHost(); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost); short x = networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength(); String n = localHost.getHostAddress() + "/" + x; SubnetUtils utils = new SubnetUtils(n); ; PdfPTable table = new PdfPTable(new float[] { 0.50f, 0.70f, 0.90f }); table = new PdfPTable(3); Paragraph p = new Paragraph(""); p.setAlignment(Element.ALIGN_CENTER); p.setSpacingAfter(30); doc.add(p); p = new Paragraph("Informaes da Network"); p.setAlignment(Element.ALIGN_CENTER); p.setSpacingAfter(30); doc.add(p); Paragraph paragraph = new Paragraph("" + utils.getInfo()); paragraph.setAlignment(Element.ALIGN_CENTER); paragraph.setSpacingAfter(30); doc.add(paragraph); table.setHorizontalAlignment(Element.ALIGN_CENTER); PdfPCell header = new PdfPCell(new Paragraph("Diagnostico do Scanner da Rede")); header.setColspan(3); table.addCell(header); table.addCell("IP"); table.addCell("HostName"); table.addCell("Portas Abertas"); for (int i = 0; i < IP.size(); i++) { table.addCell(IP.get(i)); table.addCell(NameHost.get(i)); table.addCell("" + PortasA.get(i)); } doc.add(table); } finally { if (doc != null) { doc.close(); } if (os != null) { os.close(); } } EnvioEmail sc = new EnvioEmail(); sc.EnvioEmail(); }
From source file:org.cnbi.utils.license.MacAddressUtil.java
/** * IP??Mac?//from www . java 2 s. co m * * @param ia * @return */ private static String getMacByIpAddress(InetAddress ia) { // ???mac?mac?byte try { byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress(); // System.out.println("mac" + mac.length); // ??mac??String StringBuffer sb = new StringBuffer(""); for (int i = 0; i < mac.length; i++) { if (i != 0) { sb.append(":"); } // mac[i] & 0xFF byte int temp = mac[i] & 0xff; String str = Integer.toHexString(temp); // System.out.println("?8?:" + str); if (str.length() == 1) { sb.append("0" + str); } else { sb.append(str); } } // ???mac? return sb.toString().toUpperCase(); } catch (SocketException e) { e.printStackTrace(); return getMacByCommand(); } }
From source file:nfinity.FindPeer.java
public String ScanNetwork() { try {//from w w w .j av a 2 s . c o m Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(nets)) { Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); for (InetAddress inetAddress : Collections.list(inetAddresses)) { if (!inetAddress.getClass().toString().equals("class java.net.Inet6Address")) { if (!inetAddress.isLoopbackAddress()) { try { SubnetUtils utils = new SubnetUtils(inetAddress.getHostAddress() + "/" + netint.getInterfaceAddresses().get(1).getNetworkPrefixLength()); String[] allIps = utils.getInfo().getAllAddresses(); return ConnectIP(allIps, inetAddress); } catch (IllegalArgumentException ex) { int prefix = NetworkInterface.getByInetAddress(inetAddress).getInterfaceAddresses() .get(0).getNetworkPrefixLength(); if (!inetAddress.isLoopbackAddress()) { System.out .println("IP: " + inetAddress.getHostAddress() + " Prefix: " + prefix); SubnetUtils utils = new SubnetUtils( inetAddress.getHostAddress() + "/" + prefix); String[] allIps = utils.getInfo().getAllAddresses(); return ConnectIP(allIps, inetAddress); } } } } } } } catch (SocketException ex) { System.out.println("Connection failed " + ex.getMessage()); } return "Peer not found"; }
From source file:com.jaeksoft.searchlib.util.NetworksUtils.java
public static final String getFirstHardwareAddress() throws URISyntaxException, UnknownHostException, SocketException { InetAddress localhost = InetAddress.getLocalHost(); String hardwareAddress = null; if (localhost != null) hardwareAddress = getHardwareAddress(NetworkInterface.getByInetAddress(localhost)); if (hardwareAddress != null) return hardwareAddress; Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { hardwareAddress = getHardwareAddress(networkInterfaces.nextElement()); if (hardwareAddress != null) return hardwareAddress; }//from w w w.j a v a 2s . c om return null; }
From source file:ca.viaware.dlna.ssdp.SSDPService.java
public SSDPService() { ssdpConfig = SettingsManager.getServerConfig().getJSONObject("ssdp"); httpConfig = SettingsManager.getServerConfig().getJSONObject("http"); try {//from ww w . j ava 2 s. c o m outSock = new MulticastSocket(ssdpConfig.getInt("port")); outSock.setNetworkInterface( NetworkInterface.getByInetAddress(InetAddress.getByName(ssdpConfig.getString("host")))); Log.info("SSDP: Outbound UDP bound to " + this.outSock.getLocalAddress()); } catch (IOException e) { e.printStackTrace(); } this.baseAnnounce = ""; this.baseAnnounce += "HOST: 239.255.255.250:1900\r\n"; this.baseAnnounce += "CACHE-CONTROL: max-age=1800\r\n"; this.baseAnnounce += "NTS: ssdp:alive\r\n"; this.baseAnnounce += "SERVER:" + Globals.SERVER + "\r\n"; }
From source file:org.openhab.binding.dscalarm.internal.discovery.EnvisalinkBridgeDiscovery.java
/** * Method for Bridge Discovery.//from ww w. j a v a 2s.c o m */ public synchronized void discoverBridge() { logger.debug("Starting Envisalink Bridge Discovery."); SubnetUtils subnetUtils = null; SubnetInfo subnetInfo = null; long lowIP = 0; long highIP = 0; try { InetAddress localHost = InetAddress.getLocalHost(); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost); subnetUtils = new SubnetUtils(localHost.getHostAddress() + "/" + networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength()); subnetInfo = subnetUtils.getInfo(); lowIP = convertIPToNumber(subnetInfo.getLowAddress()); highIP = convertIPToNumber(subnetInfo.getHighAddress()); } catch (IllegalArgumentException e) { logger.error("discoverBridge(): Illegal Argument Exception - {}", e.toString()); return; } catch (Exception e) { logger.error("discoverBridge(): Error - Unable to get Subnet Information! {}", e.toString()); return; } logger.debug(" Local IP Address: {} - {}", subnetInfo.getAddress(), convertIPToNumber(subnetInfo.getAddress())); logger.debug(" Subnet: {} - {}", subnetInfo.getNetworkAddress(), convertIPToNumber(subnetInfo.getNetworkAddress())); logger.debug(" Network Prefix: {}", subnetInfo.getCidrSignature().split("/")[1]); logger.debug(" Network Mask: {}", subnetInfo.getNetmask()); logger.debug(" Low IP: {}", convertNumberToIP(lowIP)); logger.debug(" High IP: {}", convertNumberToIP(highIP)); for (long ip = lowIP; ip <= highIP; ip++) { try (Socket socket = new Socket()) { ipAddress = convertNumberToIP(ip); socket.setReuseAddress(true); socket.setReceiveBufferSize(32); socket.connect(new InetSocketAddress(ipAddress, ENVISALINK_BRIDGE_PORT), CONNECTION_TIMEOUT); if (socket.isConnected()) { String message = ""; socket.setSoTimeout(SO_TIMEOUT); try (BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream()))) { message = input.readLine(); } catch (SocketTimeoutException e) { logger.error("discoverBridge(): No Message Read from Socket at [{}] - {}", ipAddress, e.getMessage()); continue; } catch (Exception e) { logger.error("discoverBridge(): Exception Reading from Socket! {}", e.toString()); continue; } if (message.substring(0, 3).equals(ENVISALINK_DISCOVERY_RESPONSE)) { logger.debug("discoverBridge(): Bridge Found - [{}]! Message - '{}'", ipAddress, message); dscAlarmBridgeDiscovery.addEnvisalinkBridge(ipAddress); } else { logger.debug("discoverBridge(): No Response from Connection - [{}]! Message - '{}'", ipAddress, message); } } } catch (IllegalArgumentException e) { logger.error("discoverBridge(): Illegal Argument Exception - {}", e.toString()); } catch (SocketTimeoutException e) { logger.trace("discoverBridge(): No Connection on Port 4025! [{}]", ipAddress); } catch (SocketException e) { logger.error("discoverBridge(): Socket Exception! [{}] - {}", ipAddress, e.toString()); } catch (IOException e) { logger.error("discoverBridge(): IO Exception! [{}] - {}", ipAddress, e.toString()); } } }