List of usage examples for java.net NetworkInterface getByInetAddress
public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException
From source file:net.bioclipse.dbxp.business.DbxpManager.java
public static String getMacAddress() throws SocketException, UnknownHostException { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); 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) ? "" : "")); }// w ww . java2 s . co m //System.out.println(sb.toString()); return sb.toString(); }
From source file:com.dhr.security.LicenseValidation.java
String getMachineMacAddress() throws UnknownHostException, SocketException { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); byte[] mac = network.getHardwareAddress(); StringBuilder currentMachineMacAddress = new StringBuilder(); for (int i = 0; i < mac.length; i++) { currentMachineMacAddress.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); }/*from ww w . j a va 2 s . c om*/ System.out.println(currentMachineMacAddress.toString()); return currentMachineMacAddress.toString(); }
From source file:org.eclipse.orion.server.authentication.formpersona.PersonaHelper.java
private static boolean isLoopback(InetAddress addr) { try {//from w ww .java2s.c o m if (addr.isLoopbackAddress()) return true; return NetworkInterface.getByInetAddress(addr) != null; } catch (SocketException e) { return false; } }
From source file:com.redhat.rhn.domain.monitoring.satcluster.SatClusterFactory.java
/** * Create a new SatCluster (scout)// w ww. j av a2s . c o m * @param user who creates the Scout * @return new instance */ public static SatCluster createSatCluster(User user) { SatCluster retval = new SatCluster(); CommandTarget ct = new CommandTarget(); ct.setOrg(user.getOrg()); ct.setTargetType("cluster"); retval.setCommandTarget(ct); retval.setOrg(user.getOrg()); retval.setPhysicalLocation(PHYSICAL_LOCATION); retval.setTargetType(ct.getTargetType()); retval.setDeployed("1"); retval.setLastUpdateUser(user.getLogin()); retval.setLastUpdateDate(new Date()); try { InetAddress ip = InetAddress.getLocalHost(); boolean haveIpv4 = ip instanceof Inet4Address; if (haveIpv4) { retval.setVip(ip.getHostAddress()); } else { retval.setVip6(ip.getHostAddress()); } NetworkInterface ni = NetworkInterface.getByInetAddress(ip); for (InterfaceAddress ifa : ni.getInterfaceAddresses()) { InetAddress ia = ifa.getAddress(); if ((ia instanceof Inet4Address) != haveIpv4) { if (haveIpv4) { retval.setVip6(ia.getHostAddress()); } else { retval.setVip(ia.getHostAddress()); } break; } } } catch (Exception e) { log.warn("Failed to find out IP host addresses. " + "Setting loopback IPs instead."); try { NetworkInterface ni = NetworkInterface.getByName("lo"); for (InterfaceAddress ifa : ni.getInterfaceAddresses()) { InetAddress ia = ifa.getAddress(); if (ia instanceof Inet4Address) { if (StringUtils.isEmpty(retval.getVip())) { retval.setVip(ia.getHostAddress()); } } else { //IPv6 if (StringUtils.isEmpty(retval.getVip6())) { retval.setVip6(ia.getHostAddress()); } } } } catch (SocketException se) { log.fatal("Failed to find out loopback IPs."); se.printStackTrace(); } } return retval; }
From source file:net.pms.network.HTTPServer.java
public boolean start() throws IOException { hostname = configuration.getServerHostname(); InetSocketAddress address;/* w ww . j a v a 2 s. c om*/ if (StringUtils.isNotBlank(hostname)) { logger.info("Using forced address " + hostname); InetAddress tempIA = InetAddress.getByName(hostname); if (tempIA != null && networkInterface != null && networkInterface.equals(NetworkInterface.getByInetAddress(tempIA))) { address = new InetSocketAddress(tempIA, port); } else { address = new InetSocketAddress(hostname, port); } } else if (isAddressFromInterfaceFound(configuration.getNetworkInterface())) { // XXX sets iafinal and networkInterface logger.info("Using address {} found on network interface: {}", iafinal, networkInterface.toString().trim().replace('\n', ' ')); address = new InetSocketAddress(iafinal, port); } else { logger.info("Using localhost address"); address = new InetSocketAddress(port); } logger.info("Created socket: " + address); if (configuration.isHTTPEngineV2()) { // HTTP Engine V2 group = new DefaultChannelGroup("myServer"); factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); HttpServerPipelineFactory pipeline = new HttpServerPipelineFactory(group); bootstrap.setPipelineFactory(pipeline); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); bootstrap.setOption("reuseAddress", true); bootstrap.setOption("child.reuseAddress", true); bootstrap.setOption("child.sendBufferSize", 65536); bootstrap.setOption("child.receiveBufferSize", 65536); channel = bootstrap.bind(address); group.add(channel); if (hostname == null && iafinal != null) { hostname = iafinal.getHostAddress(); } else if (hostname == null) { hostname = InetAddress.getLocalHost().getHostAddress(); } } else { // HTTP Engine V1 serverSocketChannel = ServerSocketChannel.open(); serverSocket = serverSocketChannel.socket(); serverSocket.setReuseAddress(true); serverSocket.bind(address); if (hostname == null && iafinal != null) { hostname = iafinal.getHostAddress(); } else if (hostname == null) { hostname = InetAddress.getLocalHost().getHostAddress(); } runnable = new Thread(this, "HTTP Server"); runnable.setDaemon(false); runnable.start(); } return true; }
From source file:org.encuestame.core.util.InternetUtils.java
/** * /* ww w .j a v a2s.c om*/ * @param addr * @return */ public static boolean isThisMyIpAddress(InetAddress addr) { // Check if the address is a valid special local or loop back if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()) return true; // Check if the address is defined on any interface try { return NetworkInterface.getByInetAddress(addr) != null; } catch (SocketException e) { return false; } }
From source file:com.adito.tunnels.forms.TunnelForm.java
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errs = super.validate(mapping, request); if (isCommiting()) { if (!Util.isNullOrTrimmedBlank(sourceInterface)) { /**/*from ww w . ja va 2 s.c o 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 ActionMessage("tunnelWizard.tunnelDetails.error.sourcePortNotInteger")); } try { int port = Integer.valueOf(destinationPort).intValue(); if (port < 1 || port > 65535) { throw new IllegalArgumentException(); } Integer.valueOf(destinationPort).intValue(); } catch (Exception e) { errs.add(Globals.ERROR_KEY, new ActionMessage("tunnelWizard.tunnelDetails.error.destinationPortNotInteger")); } if (Util.isNullOrTrimmedBlank(destinationHost)) { errs.add(Globals.ERROR_KEY, new ActionMessage("tunnelWizard.tunnelDetails.error.noDestinationHost")); } else { if (!HostnameOrIPAddressWithReplacementsValidator.isValidAsHostOrIp(destinationHost)) { errs.add(Globals.ERROR_KEY, new ActionMessage("tunnelWizard.tunnelDetails.error.invalidHost")); } } if (getResourceName().equalsIgnoreCase("default") && (!getEditing() || (getEditing() && !getResource().getResourceName().equalsIgnoreCase("default")))) { errs.add(Globals.ERROR_KEY, new ActionMessage("error.createNetworkPlace.cantUseNameDefault")); setResourceName(""); } } return errs; }
From source file:it.evilsocket.dsploit.net.Network.java
public Network(Context context) throws NoRouteToHostException, SocketException, UnknownHostException { mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); mInfo = mWifiManager.getDhcpInfo();//from w w w . j a va2s. c o m mWifiInfo = mWifiManager.getConnectionInfo(); mLocal = new IP4Address(mInfo.ipAddress); mGateway = new IP4Address(mInfo.gateway); mNetmask = getNetmask(); mBase = new IP4Address(mInfo.netmask & mInfo.gateway); if (isConnected() == false) throw new NoRouteToHostException("Not connected to any WiFi access point."); else { try { mInterface = NetworkInterface.getByInetAddress(getLocalAddress()); if (mInterface == null) throw new IllegalStateException("Error retrieving network interface."); } catch (SocketException e) { System.errorLogging(e); /* * Issue #26: Initialization error in ColdFusionX ROM * * It seems it's a ROM issue which doesn't correctly populate device descriptors. * This rom maps the default wifi interface to a generic usb device * ( maybe it's missing the specific interface driver ), which is obviously not, and * it all goes shit, use an alternative method to obtain the interface object. */ mInterface = NetworkInterface.getByName(java.lang.System.getProperty("wifi.interface", "wlan0")); if (mInterface == null) throw e; } } }
From source file:com.at.lic.LicenseControl.java
private String getMAC() throws Exception { String mac = "1:2:3:4:5:6:7:8"; // default mac address InetAddress addr = InetAddress.getLocalHost(); NetworkInterface ni = NetworkInterface.getByInetAddress(addr); if (ni.isLoopback() || ni.isVirtual()) { ni = null;//from w w w . jav a 2 s . c om Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); while (nis.hasMoreElements()) { NetworkInterface aNI = (NetworkInterface) nis.nextElement(); if (!aNI.isLoopback() && !aNI.isVirtual()) { ni = aNI; break; } } } if (ni != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); byte[] HAs = ni.getHardwareAddress(); for (int i = 0; i < HAs.length; i++) { ps.format("%02X:", HAs[i]); } mac = baos.toString(); if (mac.length() > 0) { mac = mac.replaceFirst(":$", ""); } ps.close(); baos.close(); } return mac; }
From source file:org.csploit.android.net.Network.java
public Network(Context context) throws SocketException, UnknownHostException { mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); mInfo = mWifiManager.getDhcpInfo();// w w w . ja va2s . co m mWifiInfo = mWifiManager.getConnectionInfo(); mLocal = new IP4Address(mInfo.ipAddress); mGateway = new IP4Address(mInfo.gateway); mNetmask = getNetmask(); mBase = new IP4Address(mInfo.netmask & mInfo.gateway); if (isConnected() == false) throw new NoRouteToHostException("Not connected to any WiFi access point."); else { try { mInterface = NetworkInterface.getByInetAddress(getLocalAddress()); if (mInterface == null) throw new IllegalStateException("Error retrieving network interface."); } catch (SocketException e) { System.errorLogging(e); /* * Issue #26: Initialization error in ColdFusionX ROM * * It seems it's a ROM issue which doesn't correctly populate device descriptors. * This rom maps the default wifi interface to a generic usb device * ( maybe it's missing the specific interface driver ), which is obviously not, and * it all goes shit, use an alternative method to obtain the interface object. */ mInterface = NetworkInterface.getByName(java.lang.System.getProperty("wifi.interface", "wlan0")); if (mInterface == null) throw e; } } }