当前位置: 首页>>代码示例>>Java>>正文


Java NetworkInterface.getByName方法代码示例

本文整理汇总了Java中java.net.NetworkInterface.getByName方法的典型用法代码示例。如果您正苦于以下问题:Java NetworkInterface.getByName方法的具体用法?Java NetworkInterface.getByName怎么用?Java NetworkInterface.getByName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.net.NetworkInterface的用法示例。


在下文中一共展示了NetworkInterface.getByName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getMacAddress

import java.net.NetworkInterface; //导入方法依赖的package包/类
public static byte[] getMacAddress() {
	String networkInterfaceConfig = getPropertyValue("network.interface").toString();
	NetworkInterface nif = null;
	byte[] macAddress = null;
	
	try {
		if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
			nif = NetworkInterface.getByIndex(Integer.parseInt(networkInterfaceConfig));
		} else {
			nif = NetworkInterface.getByName(networkInterfaceConfig);
		}
		macAddress = nif.getHardwareAddress();
	} catch (SocketException e) {
		getLogger().error("Failed to retrieve local mac address (SocketException)", e);
	}
	
	return macAddress;
}
 
开发者ID:V2GClarity,项目名称:RISE-V2G,代码行数:19,代码来源:MiscUtils.java

示例2: getMacAddress

import java.net.NetworkInterface; //导入方法依赖的package包/类
public static String getMacAddress() {
    String macAddress = null;
    StringBuffer buf = new StringBuffer();
    NetworkInterface networkInterface = null;
    try {
        networkInterface = NetworkInterface.getByName("eth1");
        if (networkInterface == null) {
            networkInterface = NetworkInterface.getByName("wlan0");
        }
        if (networkInterface == null) {
            return "02:00:00:00:00:02";
        }
        byte[] addr = networkInterface.getHardwareAddress();
        for (byte b : addr) {
            buf.append(String.format("%02X:", b));
        }
        if (buf.length() > 0) {
            buf.deleteCharAt(buf.length() - 1);
        }
        macAddress = buf.toString();
    } catch (SocketException e) {
        e.printStackTrace();
        return "02:00:00:00:00:02";
    }
    return macAddress;
}
 
开发者ID:ymqq,项目名称:CommonFramework,代码行数:27,代码来源:AndroidUtils.java

示例3: getInternalIpv4

import java.net.NetworkInterface; //导入方法依赖的package包/类
private final String getInternalIpv4() throws IOException
{
    NetworkInterface i = NetworkInterface.getByName("eth0");
    for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements(); )
    {
        InetAddress addr = (InetAddress) en2.nextElement();
        if (!addr.isLoopbackAddress())
        {
            if (addr instanceof Inet4Address)
            {
                return addr.getHostAddress();
            }
        }
    }
    InetAddress inet = Inet4Address.getLocalHost();
    return inet == null ? "0.0.0.0" : inet.getHostAddress();
}
 
开发者ID:SamaGames,项目名称:Hydroangeas,代码行数:18,代码来源:HydroangeasClient.java

示例4: main

import java.net.NetworkInterface; //导入方法依赖的package包/类
public static void main(String[] args) throws IOException {
    Scanner s = new Scanner(new File(args[0]));
    try {
        while (s.hasNextLine()) {
            String link = s.nextLine();
            NetworkInterface ni = NetworkInterface.getByName(link);
            if (ni != null) {
                Enumeration<InetAddress> addrs = ni.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress addr = addrs.nextElement();
                    System.out.println(addr.getHostAddress());
                }
            }
        }
    } finally {
        s.close();
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:19,代码来源:ProbeIB.java

示例5: getLocalIP

import java.net.NetworkInterface; //导入方法依赖的package包/类
public void getLocalIP() {

            NetworkInterface ni = null;
            try {
                ni = NetworkInterface.getByName("eth0");
            } catch (SocketException e) {
                e.printStackTrace();
            }
            Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();

            while (inetAddresses.hasMoreElements())

            {
                InetAddress ia = inetAddresses.nextElement();
                if (!ia.isLinkLocalAddress()) {
                    localIP = ia;
                    break;
                }
            }
        }
 
开发者ID:shlee89,项目名称:athena,代码行数:21,代码来源:Main.java

示例6: getNetworkInterfaceAddress

import java.net.NetworkInterface; //导入方法依赖的package包/类
private static InetAddress getNetworkInterfaceAddress(String intf, String configName, boolean preferIPv6) throws ConfigurationException
{
    try
    {
        NetworkInterface ni = NetworkInterface.getByName(intf);
        if (ni == null)
            throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" could not be found", false);
        Enumeration<InetAddress> addrs = ni.getInetAddresses();
        if (!addrs.hasMoreElements())
            throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" was found, but had no addresses", false);

        /*
         * Try to return the first address of the preferred type, otherwise return the first address
         */
        InetAddress retval = null;
        while (addrs.hasMoreElements())
        {
            InetAddress temp = addrs.nextElement();
            if (preferIPv6 && temp instanceof Inet6Address) return temp;
            if (!preferIPv6 && temp instanceof Inet4Address) return temp;
            if (retval == null) retval = temp;
        }
        return retval;
    }
    catch (SocketException e)
    {
        throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" caused an exception", e);
    }
}
 
开发者ID:Netflix,项目名称:sstable-adaptor,代码行数:30,代码来源:DatabaseDescriptor.java

示例7: convert

import java.net.NetworkInterface; //导入方法依赖的package包/类
public NetworkInterface convert(String s) throws Exception {
    try {
        InetAddress addr = new InetAddressConverter().convert(s);
        return NetworkInterface.getByInetAddress(addr);
    } catch (Exception ex) {
        try { return NetworkInterface.getByName(s);
        } catch (Exception ex2) {
            throw new TypeConversionException("'" + s + "' is not an InetAddress or NetworkInterface name");
        }
    }
}
 
开发者ID:remkop,项目名称:picocli,代码行数:12,代码来源:CommandLine.java

示例8: getIPs

import java.net.NetworkInterface; //导入方法依赖的package包/类
/**
 * Returns all the IPs associated with the provided interface, if any, in
 * textual form.
 * 
 * @param strInterface
 *            The name of the network interface or sub-interface to query
 *            (eg eth0 or eth0:0) or the string "default"
 * @param returnSubinterfaces
 *            Whether to return IPs associated with subinterfaces of
 *            the given interface
 * @return A string vector of all the IPs associated with the provided
 *         interface. The local host IP is returned if the interface
 *         name "default" is specified or there is an I/O error looking
 *         for the given interface.
 * @throws UnknownHostException
 *             If the given interface is invalid
 * 
 */
public static String[] getIPs(String strInterface,
    boolean returnSubinterfaces) throws UnknownHostException {
  if ("default".equals(strInterface)) {
    return new String[] { cachedHostAddress };
  }
  NetworkInterface netIf;
  try {
    netIf = NetworkInterface.getByName(strInterface);
    if (netIf == null) {
      netIf = getSubinterface(strInterface);
    }
  } catch (SocketException e) {
    LOG.warn("I/O error finding interface " + strInterface +
        ": " + e.getMessage());
    return new String[] { cachedHostAddress };
  }
  if (netIf == null) {
    throw new UnknownHostException("No such interface " + strInterface);
  }

  // NB: Using a LinkedHashSet to preserve the order for callers
  // that depend on a particular element being 1st in the array.
  // For example, getDefaultIP always returns the first element.
  LinkedHashSet<InetAddress> allAddrs = new LinkedHashSet<InetAddress>();
  allAddrs.addAll(Collections.list(netIf.getInetAddresses()));
  if (!returnSubinterfaces) {
    allAddrs.removeAll(getSubinterfaceInetAddrs(netIf));
  }

  String ips[] = new String[allAddrs.size()];
  int i = 0;
  for (InetAddress addr : allAddrs) {
    ips[i++] = addr.getHostAddress();
  }
  return ips;
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:55,代码来源:DNS.java

示例9: getIPsAsInetAddressList

import java.net.NetworkInterface; //导入方法依赖的package包/类
/**
 * Returns all the IPs associated with the provided interface, if any, as
 * a list of InetAddress objects.
 *
 * @param strInterface
 *            The name of the network interface or sub-interface to query
 *            (eg eth0 or eth0:0) or the string "default"
 * @param returnSubinterfaces
 *            Whether to return IPs associated with subinterfaces of
 *            the given interface
 * @return A list of all the IPs associated with the provided
 *         interface. The local host IP is returned if the interface
 *         name "default" is specified or there is an I/O error looking
 *         for the given interface.
 * @throws UnknownHostException
 *             If the given interface is invalid
 *
 */
public static List<InetAddress> getIPsAsInetAddressList(String strInterface,
    boolean returnSubinterfaces) throws UnknownHostException {
  if ("default".equals(strInterface)) {
    return Arrays.asList(InetAddress.getByName(cachedHostAddress));
  }
  NetworkInterface netIf;
  try {
    netIf = NetworkInterface.getByName(strInterface);
    if (netIf == null) {
      netIf = getSubinterface(strInterface);
    }
  } catch (SocketException e) {
    LOG.warn("I/O error finding interface " + strInterface +
        ": " + e.getMessage());
    return Arrays.asList(InetAddress.getByName(cachedHostAddress));
  }
  if (netIf == null) {
    throw new UnknownHostException("No such interface " + strInterface);
  }

  // NB: Using a LinkedHashSet to preserve the order for callers
  // that depend on a particular element being 1st in the array.
  // For example, getDefaultIP always returns the first element.
  LinkedHashSet<InetAddress> allAddrs = new LinkedHashSet<InetAddress>();
  allAddrs.addAll(Collections.list(netIf.getInetAddresses()));
  if (!returnSubinterfaces) {
    allAddrs.removeAll(getSubinterfaceInetAddrs(netIf));
  }
  return new Vector<InetAddress>(allAddrs);
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:49,代码来源:DNS.java

示例10: parseAdapterName

import java.net.NetworkInterface; //导入方法依赖的package包/类
/**
 * Parse an adapter name string and return the matching address
 * 
 * @param adapter String
 * @return InetAddress
 * @exception InvalidConfigurationException
 */
protected final InetAddress parseAdapterName(String adapter)
  throws InvalidConfigurationException {

  NetworkInterface ni = null;
  
  try {
    ni = NetworkInterface.getByName( adapter);
  }
  catch (SocketException ex) {
    throw new InvalidConfigurationException( "Invalid adapter name, " + adapter);
  }
  
  if ( ni == null)
    throw new InvalidConfigurationException( "Invalid network adapter name, " + adapter);
  
  // Get the IP address for the adapter

  InetAddress adapAddr = null;
  Enumeration<InetAddress> addrEnum = ni.getInetAddresses();
  
  while ( addrEnum.hasMoreElements() && adapAddr == null) {
    
    // Get the current address
    
    InetAddress addr = addrEnum.nextElement();
    if ( IPAddress.isNumericAddress( addr.getHostAddress()))
      adapAddr = addr;
  }
  
  // Check if we found the IP address to bind to
  
  if ( adapAddr == null)
    throw new InvalidConfigurationException( "Adapter " + adapter + " does not have a valid IP address");

  // Return the adapter address
  
  return adapAddr;
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:46,代码来源:AbstractServerConfigurationBean.java

示例11: getLinkLocalAddress

import java.net.NetworkInterface; //导入方法依赖的package包/类
/**
 * Determines the link-local IPv6 address which is configured on the network interface provided
 * in the properties file.
 * @return The link-local address given as a String
 */
public static Inet6Address getLinkLocalAddress() {
	String networkInterfaceConfig = getPropertyValue("network.interface").toString();
	
	NetworkInterface nif = null;
	
	try {
		if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
			nif = NetworkInterface.getByIndex(Integer.parseInt(networkInterfaceConfig));
		} else {
			nif = NetworkInterface.getByName(networkInterfaceConfig);
		}
		Enumeration<InetAddress> inetAddresses = nif.getInetAddresses();
		
		while (inetAddresses.hasMoreElements()) {
			InetAddress inetAddress = inetAddresses.nextElement();
			
			if (inetAddress.getClass() == Inet6Address.class && inetAddress.isLinkLocalAddress()) {
				return (Inet6Address) inetAddress;
			}
		}
		
		getLogger().fatal("No IPv6 link-local address found on the network interface '" +
				nif.getDisplayName() + "' configured in the properties file");
	} catch (SocketException e) {
		getLogger().fatal("SocketException while trying to get network interface for configured name " +
						  networkInterfaceConfig + "'", e); 
	} catch (NullPointerException | NumberFormatException e2) {
		getLogger().fatal("No network interface for configured network interface index '" + 
						  networkInterfaceConfig + "' found");
	}
	
	return null;
}
 
开发者ID:V2GClarity,项目名称:RISE-V2G,代码行数:39,代码来源:MiscUtils.java

示例12: onWifiP2pGroupChange

import java.net.NetworkInterface; //导入方法依赖的package包/类
/** Handle a change notification about the wifi p2p group. */
private void onWifiP2pGroupChange(WifiP2pGroup wifiP2pGroup) {
  if (wifiP2pGroup == null || wifiP2pGroup.getInterface() == null) {
    return;
  }

  NetworkInterface wifiP2pInterface;
  try {
    wifiP2pInterface = NetworkInterface.getByName(wifiP2pGroup.getInterface());
  } catch (SocketException e) {
    Logging.e(TAG, "Unable to get WifiP2p network interface", e);
    return;
  }

  List<InetAddress> interfaceAddresses = Collections.list(wifiP2pInterface.getInetAddresses());
  IPAddress[] ipAddresses = new IPAddress[interfaceAddresses.size()];
  for (int i = 0; i < interfaceAddresses.size(); ++i) {
    ipAddresses[i] = new IPAddress(interfaceAddresses.get(i).getAddress());
  }

  wifiP2pNetworkInfo =
      new NetworkInformation(
          wifiP2pGroup.getInterface(),
          ConnectionType.CONNECTION_WIFI,
          WIFI_P2P_NETWORK_HANDLE,
          ipAddresses);
  observer.onNetworkConnect(wifiP2pNetworkInfo);
}
 
开发者ID:Piasy,项目名称:AppRTC-Android,代码行数:29,代码来源:NetworkMonitorAutoDetect.java

示例13: getAddressesForInterface

import java.net.NetworkInterface; //导入方法依赖的package包/类
/** Returns addresses for the given interface (it must be marked up) */
static InetAddress[] getAddressesForInterface(String name) throws SocketException {
    NetworkInterface intf = NetworkInterface.getByName(name);
    if (intf == null) {
        throw new IllegalArgumentException("No interface named '" + name + "' found, got " + getInterfaces());
    }
    if (!intf.isUp()) {
        throw new IllegalArgumentException("Interface '" + name + "' is not up and running");
    }
    List<InetAddress> list = Collections.list(intf.getInetAddresses());
    if (list.isEmpty()) {
        throw new IllegalArgumentException("Interface '" + name + "' has no internet addresses");
    }
    return list.toArray(new InetAddress[list.size()]);
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:16,代码来源:NetworkUtils.java

示例14: getMacOsIdentifier

import java.net.NetworkInterface; //导入方法依赖的package包/类
private static String getMacOsIdentifier() throws SocketException, NoSuchAlgorithmException {
    NetworkInterface networkInterface = NetworkInterface.getByName("en0");
    byte[] hardwareAddress = networkInterface.getHardwareAddress();
    return Utils.hexStringify(Utils.sha256Hash(hardwareAddress));
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:6,代码来源:ComputerIdentifierGenerator.java

示例15: run

import java.net.NetworkInterface; //导入方法依赖的package包/类
public void run(String[] args)
{
	Runtime.getRuntime().addShutdownHook(new ShutdownHook(this));
	
	File uuidFile = new File(UUID_FILE);
	File configFile = new File(CONFIG_FILE);
	
	System.out.println("Starting Pi YouTube...");
	
	this.deviceUUID = this.getThisDeviceUUID(uuidFile);
	System.out.println("Loaded device UUID. UUID: " + this.deviceUUID);
	
	this.loadConfig(configFile);
	
	if(this.config.optBoolean("preloadchrome") == true)
	{
		System.out.println("Starting Chrome...");
		this.launchChromeDriver();
		System.out.println("Chrome started!");
	}

	try
	{
		this.ssdpServers = new ArrayList<SSDPServer>();
		NetworkInterface iface = null;
		
		if(this.config.optString("iface", null) != null && (iface = NetworkInterface.getByName(this.config.getString("iface"))) != null)
		{
			this.ssdpServers.add(new SSDPServer(this.deviceUUID, iface, DIAL_PORT));
		}
		else
		{
			if(Util.isUnix())
			{
				System.out.println("Interface needs to be defined for Linux systems. Please edit config.json.");
				System.exit(0);
			}
			
			for(NetworkInterface iface2 : Collections.list(NetworkInterface.getNetworkInterfaces()))
			{
				if(iface2.isUp())
				{
					this.ssdpServers.add(new SSDPServer(this.deviceUUID, iface2, DIAL_PORT));
				}
			}
		}
		
		this.dialServer = new DIALServer(this, DIAL_PORT);
		this.dialServer.start();
		
		System.out.println("DIAL server started!");
		
		for(SSDPServer server : this.ssdpServers)
		{
			server.start();
		}
		
		System.out.println("SSDP server(s) started!");
		
		System.out.println("Pi YouTube ready to accept connections!");
	}
	catch (IOException e)
	{
		e.printStackTrace();
	}
}
 
开发者ID:Spajker7,项目名称:PiYouTube,代码行数:67,代码来源:PiYouTube.java


注:本文中的java.net.NetworkInterface.getByName方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。