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


Java NetworkInterface类代码示例

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


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

示例1: JdpBroadcaster

import java.net.NetworkInterface; //导入依赖的package包/类
/**
 * Create a new broadcaster
 *
 * @param address - multicast group address
 * @param srcAddress - address of interface we should use to broadcast.
 * @param port - udp port to use
 * @param ttl - packet ttl
 * @throws IOException
 */
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
        throws IOException, JdpException {
    this.addr = address;
    this.port = port;

    ProtocolFamily family = (address instanceof Inet6Address)
            ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;

    channel = DatagramChannel.open(family);
    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);

    // with srcAddress equal to null, this constructor do exactly the same as
    // if srcAddress is not passed
    if (srcAddress != null) {
        // User requests particular interface to bind to
        NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
        try {
            channel.bind(new InetSocketAddress(srcAddress, 0));
        } catch (UnsupportedAddressTypeException ex) {
            throw new JdpException("Unable to bind to source address");
        }
        channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:35,代码来源:JdpBroadcaster.java

示例2: getDeviceNetworkIp

import java.net.NetworkInterface; //导入依赖的package包/类
/**
 * 获取手机ip地址,如果WiFi可以,则返回WiFi的ip,否则就返回网络ip.
 *
 * @param context 上下文
 * @return ip
 */
public static String getDeviceNetworkIp(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context
            .CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if (networkInfo != null) {
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {  //wifi
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifi.getConnectionInfo();
            int ip = wifiInfo.getIpAddress();
            return convertToIp(ip);
        } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // gprs
            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
                     en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                         enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        //这里4.0以上部分手机返回的地址将会是ipv6地址,而且在4G下也验证了返回的是
                        //ipv6,而服务器不处理ipv6地址
                        if (!inetAddress.isLoopbackAddress() && !(inetAddress
                                instanceof Inet6Address)) {
                            return inetAddress.getHostAddress().toString();
                        }

                    }

                }
            } catch (SocketException e) {
                Log.e(TAG, "e", e);
            }
        }
    }
    return DEFAULT_NETWORK_IP;
}
 
开发者ID:facetome,项目名称:smart_plan,代码行数:42,代码来源:Utilty.java

示例3: getMacAddressByNetworkInterface

import java.net.NetworkInterface; //导入依赖的package包/类
/**
 * <p>need permission {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
 */
private static String getMacAddressByNetworkInterface() {
    try {
        List<NetworkInterface> nis = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface ni : nis) {
            if (!ni.getName().equalsIgnoreCase("wlan0")) continue;
            byte[] macBytes = ni.getHardwareAddress();
            if (macBytes != null && macBytes.length > 0) {
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02x:", b));
                }
                return res1.deleteCharAt(res1.length() - 1).toString();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "02:00:00:00:00:00";
}
 
开发者ID:ChangsenLai,项目名称:codedemos,代码行数:23,代码来源:DeviceUtil.java

示例4: getIPv4s

import java.net.NetworkInterface; //导入依赖的package包/类
public static ArrayList<String> getIPv4s() {
	ArrayList<String> IPs = new ArrayList<String>();
	
	Enumeration<NetworkInterface> interfaces = null;
	try {
		interfaces = NetworkInterface.getNetworkInterfaces();
	} catch (SocketException e1) {
		e1.printStackTrace();
	}
	
	while(interfaces.hasMoreElements()) {
		NetworkInterface thisinterface = interfaces.nextElement();
		Enumeration<InetAddress> addresses = thisinterface.getInetAddresses();
		while(addresses.hasMoreElements()) {
			String IP = addresses.nextElement().getHostAddress();
			if(Pdot.split(IP).length == 4 && !IP.equals("127.0.0.1")) {	// 255.255.255.255 = 4 dots
				IPs.add(IP);
			}
		}
	}
	
	return IPs;
}
 
开发者ID:jlxip,项目名称:LANClipboard,代码行数:24,代码来源:LAN.java

示例5: isSoftwareVirtualAdapter

import java.net.NetworkInterface; //导入依赖的package包/类
/**
 * Tries to guess if the network interface is a virtual adapter
 * by one of the makers of virtualization solutions (e.g. VirtualBox,
 * VMware, etc). This is by no means a bullet proof method which is
 * why it errs on the side of caution.
 * 
 * @param nif network interface
 * @return 
 */
public static boolean isSoftwareVirtualAdapter(NetworkInterface nif) {
    
    try {
        // VirtualBox uses a semi-random MAC address for their adapter
        // where the first 3 bytes are always the same:
        //    Windows, Mac OS X, Linux : begins with 0A-00-27
        //    Solaris:  begins with 10-00-27
        // (above from VirtualBox source code)
        //
        byte[] macAddress = nif.getHardwareAddress();
        if (macAddress != null & macAddress.length >= 3) {
            if ((macAddress[0] == 0x0A || macAddress[0] == 0x08) &&
                    (macAddress[1] == 0x00) &&
                    (macAddress[2] == 0x27)) {                
                return true;
            }
        }
        return false;
    } catch (SocketException ex) {
        return false;
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:32,代码来源:LocalAddressUtils.java

示例6: getUserId

import java.net.NetworkInterface; //导入依赖的package包/类
private String getUserId(Projectile projectile) {
    final Identity identity = projectile.getOpenShiftIdentity();
    String userId;
    // User ID will be the token
    if (identity instanceof TokenIdentity) {
        userId = ((TokenIdentity) identity).getToken();
    } else {
        // For users authenticating with user/password (ie. local/Minishift/CDK)
        // let's identify them by their MAC address (which in a VM is the MAC address
        // of the VM, or a fake one, but all we can really rely on to uniquely identify
        // an installation
        final StringBuilder sb = new StringBuilder();
        try {
            byte[] macAddress = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();
            sb.append(LOCAL_USER_ID_PREFIX);
            for (int i = 0; i < macAddress.length; i++) {
                sb.append(String.format("%02X%s", macAddress[i], (i < macAddress.length - 1) ? "-" : ""));
            }
            userId = sb.toString();
        } catch (Exception e) {
            userId = LOCAL_USER_ID_PREFIX + "UNKNOWN";
        }
    }
    return userId;
}
 
开发者ID:fabric8-launcher,项目名称:launcher-backend,代码行数:26,代码来源:MissionControlImpl.java

示例7: getGlobalAddresses

import java.net.NetworkInterface; //导入依赖的package包/类
/** Returns all global scope addresses for interfaces that are up. */
static InetAddress[] getGlobalAddresses() throws SocketException {
    List<InetAddress> list = new ArrayList<>();
    for (NetworkInterface intf : getInterfaces()) {
        if (intf.isUp()) {
            for (InetAddress address : Collections.list(intf.getInetAddresses())) {
                if (address.isLoopbackAddress() == false && 
                    address.isSiteLocalAddress() == false &&
                    address.isLinkLocalAddress() == false) {
                    list.add(address);
                }
            }
        }
    }
    if (list.isEmpty()) {
        throw new IllegalArgumentException("No up-and-running global-scope (public) addresses found, got " + getInterfaces());
    }
    return list.toArray(new InetAddress[list.size()]);
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:20,代码来源:NetworkUtils.java

示例8: getMacByInterface

import java.net.NetworkInterface; //导入依赖的package包/类
private static String getMacByInterface() throws SocketException {
    List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    for (NetworkInterface networkInterface : networkInterfaces) {
        if (networkInterface.getName().equalsIgnoreCase("wlan0")) {
            byte[] macBytes = networkInterface.getHardwareAddress();
            if (macBytes == null) {
                return null;
            }

            StringBuilder mac = new StringBuilder();
            for (byte b : macBytes) {
                mac.append(String.format("%02X:", b));
            }

            if (mac.length() > 0) {
                mac.deleteCharAt(mac.length() - 1);
            }
            return mac.toString();
        }
    }
    return null;
}
 
开发者ID:hyb1996,项目名称:Auto.js,代码行数:23,代码来源:Device.java

示例9: getInterfaceIp

import java.net.NetworkInterface; //导入依赖的package包/类
/**
 * Returns interface IP by index.
 *
 * @param interfaceIndex interface index
 * @return interface IP by index
 */
private static Ip4Address getInterfaceIp(int interfaceIndex) {
    Ip4Address ipAddress = null;
    try {
        NetworkInterface networkInterface = NetworkInterface.getByIndex(interfaceIndex);
        Enumeration ipAddresses = networkInterface.getInetAddresses();
        while (ipAddresses.hasMoreElements()) {
            InetAddress address = (InetAddress) ipAddresses.nextElement();
            if (!address.isLinkLocalAddress()) {
                ipAddress = Ip4Address.valueOf(address.getAddress());
                break;
            }
        }
    } catch (Exception e) {
        log.debug("Error while getting Interface IP by index");
        return OspfUtil.DEFAULTIP;
    }
    return ipAddress;
}
 
开发者ID:shlee89,项目名称:athena,代码行数:25,代码来源:OspfConfigUtil.java

示例10: isInterfaceAvailable

import java.net.NetworkInterface; //导入依赖的package包/类
@Override
public boolean isInterfaceAvailable(String ifaceName) throws SocketException {

    /*
     * String[]ifaces = getAvailableInterfaces(); if(ifaces == null ||
     * ifaces.length == 0){ return false; }
     * 
     * for(String name : ifaces){
     * 
     * if (name.equals(ifaceName)){ return true; } }
     * 
     * return false;
     */

    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface nif = interfaces.nextElement();
        String nm = nif.getName();
        if (nm.equals(ifaceName)) {
            return true;
        }
    }
    return false;

}
 
开发者ID:vaginessa,项目名称:RepWifiApp,代码行数:26,代码来源:Engine.java

示例11: d

import java.net.NetworkInterface; //导入依赖的package包/类
public static String d() {
    try {
        Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            Enumeration inetAddresses = ((NetworkInterface) networkInterfaces.nextElement()).getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = (InetAddress) inetAddresses.nextElement();
                if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (Exception e) {
        z.d();
        e.printStackTrace();
    }
    return "";
}
 
开发者ID:JackChan1999,项目名称:letv,代码行数:19,代码来源:a.java

示例12: getIpAddress

import java.net.NetworkInterface; //导入依赖的package包/类
private String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {

            NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();

            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }
    return ip;
}
 
开发者ID:yuvaraj119,项目名称:WifiChatSharing,代码行数:24,代码来源:MessageActivity.java

示例13: getSubinterface

import java.net.NetworkInterface; //导入依赖的package包/类
/**
 * @return NetworkInterface for the given subinterface name (eg eth0:0)
 *    or null if no interface with the given name can be found  
 */
private static NetworkInterface getSubinterface(String strInterface)
    throws SocketException {
  Enumeration<NetworkInterface> nifs = 
    NetworkInterface.getNetworkInterfaces();
    
  while (nifs.hasMoreElements()) {
    Enumeration<NetworkInterface> subNifs = 
      nifs.nextElement().getSubInterfaces();

    while (subNifs.hasMoreElements()) {
      NetworkInterface nif = subNifs.nextElement();
      if (nif.getName().equals(strInterface)) {
        return nif;
      }
    }
  }
  return null;
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:23,代码来源:DNS.java

示例14: getLocalInetAddress

import java.net.NetworkInterface; //导入依赖的package包/类
public static List<String> getLocalInetAddress() {
    List<String> inetAddressList = new ArrayList<String>();
    try {
        Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
            NetworkInterface networkInterface = enumeration.nextElement();
            Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
            while (addrs.hasMoreElements()) {
                inetAddressList.add(addrs.nextElement().getHostAddress());
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException("get local inet address fail", e);
    }

    return inetAddressList;
}
 
开发者ID:lyy4j,项目名称:rmq4note,代码行数:18,代码来源:MixAll.java

示例15: 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


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