Java获取操作系统的本机ip和Mac地址

  1. 获取局域网ip和mac(如果电脑没有直接连接外网),否则获取公网ip

  2. 通过第三放获取公网ip

public class NetworkUtils {

	/**
	 * 获取本地IP列表(针对多网卡情况)
	 * @return
	 */
	public static Map<String, Object> getLocalInetMac() {

		Map<String, Object> ipMacInfo = null;
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface networkInterface = networkInterfaces
						.nextElement();
				Enumeration<InetAddress> inetAddresses = networkInterface
						.getInetAddresses();

				while (inetAddresses.hasMoreElements()) {
					InetAddress inetAddress = inetAddresses.nextElement();
					ipMacInfo = pickInetAddress(inetAddress, networkInterface);
					if (ipMacInfo != null) {
					        Log.e("IP-MAC-1",ipMacInfo );
						return ipMacInfo;
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static Map<String, Object> pickInetAddress(InetAddress inetAddress,
			NetworkInterface ni) {
		try {
			String name = ni.getDisplayName();
			if (name.contains("Adapter")
					|| name.contains("Virtual") || name.contains("VMnet") || name.contains("#")) {
				return null;
			}
			if (ni.isVirtual() || !ni.isUp() || !ni.supportsMulticast()) {
				return null;
			}

			if (inetAddress.isSiteLocalAddress()) {
				Formatter formatter = new Formatter();
				String sMAC = null;
				byte[] macBuf = ni.getHardwareAddress();
				for (int i = 0; i < macBuf.length; i++) {
					sMAC = formatter.format(Locale.getDefault(), "%02X%s",
							macBuf[i], (i < macBuf.length - 1) ? "-" : "")
							.toString();
				}
				formatter.close();
				Map<String, Object> ipMacInfo = new HashMap<String, Object>();
				ipMacInfo.put("hostname", inetAddress.getHostName()); //系统当前hostname
				ipMacInfo.put("ip", inetAddress.getHostAddress()); //ip地址
				ipMacInfo.put("ipnet", inetAddressTypeName(inetAddress)); //网络类型
				ipMacInfo.put("os", System.getProperty("os.name")); //系统名称
				ipMacInfo.put("mac", sMAC); //mac 地址
				ipMacInfo.put("cpu-arch", System.getProperty("os.arch")); //cpu架构
				ipMacInfo.put("network-arch", ni.getDisplayName()); //网卡名称
				return ipMacInfo;
			}

		} catch (SocketException e) {
			e.printStackTrace();
		} 
		return null;
	}

	private static String inetAddressTypeName(InetAddress inetAddress) {
		return (inetAddress instanceof Inet4Address) ? "ipv4" : "ipv6";
	}

	//通过第三方网站http://1111.ip138.com/ic.asp获取ip
    public static Map<String, String> getOpenNetworkIp() 
    {
		
		try {
			URLConnection openConnection = new URL("http://1111.ip138.com/ic.asp").openConnection();
			openConnection.setDoInput(true);
			openConnection.connect();
			InputStream is =  (InputStream) openConnection.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,Charset.forName("GBK")));
			StringBuilder sb = new StringBuilder();
			String str = null;
			while((str=br.readLine())!=null)
			{
				sb.append(str);
			}
			String htmlSrc = sb.toString().toLowerCase(Locale.getDefault());
			String startTag = "<center>";
			String endTag = "</center>";
			htmlSrc = htmlSrc.substring(htmlSrc.indexOf(startTag)+startTag.length(), htmlSrc.lastIndexOf(endTag));
			String openIp = htmlSrc.substring(htmlSrc.indexOf("[")+1, htmlSrc.lastIndexOf("]"));
			String provider = htmlSrc.substring(htmlSrc.lastIndexOf(":")+1);
			
			Map<String, String> resultMap = new HashMap<String, String>();
			resultMap.put("openIp", openIp);
			resultMap.put("provider", provider);
			
			br.close();
			Log.wtf("IP-Mac-3",resultMap);
			return resultMap;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	 public static String getDNSIp(String url) throws UnknownHostException
	 {
		InetAddress bupt=null;
		try{ 
			bupt = InetAddress.getByName(url);
			return bupt.getHostAddress();
				 
		}catch(UnknownException e) {
				e.printStackTrace();
		 }
			 return null;
	 }

	 /**
	 * 检测http网络连接是否正常
	 * @param urlStr
	 * @return
	 */
	private static boolean httpIsAvaliable(String urlStr) {
		URL url = null;
		InputStream in = null;
		try {
			url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			conn.connect();
			in = conn.getInputStream();
			if (in != null && in.read() >= 0) {
				return true;
			}

		} catch (Exception e) {
			return false;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
		return false;
	}
	
	/**
	 * 检测任意ip:port网络访问是否正常
	 * @param hostname
	 * @param port
	 * @return
	 */
	private static boolean socketIsAvaiable(String hostname,int port)
	{
		Socket socket = null;
		try {
			socket = new Socket();
			socket.setKeepAlive(true);
			socket.setTcpNoDelay(true);
			socket.setTrafficClass(0x08);
			socket.connect(new InetSocketAddress(hostname, port));
			if(!socket.isClosed() && socket.isConnected() && !socket.isInputShutdown() && !socket.isOutputShutdown())
			{
				return true;
			}
		} catch (SocketException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}finally{
			if(socket!=null && !socket.isClosed())
			{
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return false;
	}
	public static void main(String[] args) {
		Map<String, Object> localInetMac = getLocalInetMac();
		System.out.println(localInetMac);
		Map<String, String> openNetworkIp = getOpenNetworkIp();
		System.out.println(openNetworkIp);

	}
}

如上方案在Android,Windows,linux都成功了,可能有些地方考虑不太周全,但应该覆盖了90-95%的PC和Android系统,对了,貌似不支持Android 2.2,


不过Android本身就可获取mac和IP,代码如下

	 public Map<String, Object>  getLocalNetworkinfo( )
	 {  
		 
		Map<String, Object> ipNetInfo = new HashMap<String, Object>();
	        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
	        WifiInfo connInfo = wifiManager.getConnectionInfo();
	        String macAddress = connInfo.getMacAddress();//mac地址
	        String ssid = connInfo.getSSID(); //ssid
	        String bssid = connInfo.getBSSID(); 
	        int rssi = connInfo.getRssi();//信号强度
	        String speed = connInfo.getLinkSpeed()+WifiInfo.LINK_SPEED_UNITS;//网速
	        int networkId = connInfo.getNetworkId(); //网络号
	        String ip = Formatter.formatIpAddress(connInfo.getIpAddress());
	        
	        DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();  
	        String gateway = Formatter.formatIpAddress(dhcpInfo.gateway);//网关
	        String netmask = Formatter.formatIpAddress(dhcpInfo.netmask);//子网掩码
	        
	        ipNetInfo.put("mac", macAddress);
	        ipNetInfo.put("ip", ip);
	        ipNetInfo.put("gateway", gateway);
	        ipNetInfo.put("netmask", netmask);
	        ipNetInfo.put("ssid", ssid);
	        ipNetInfo.put("rssi", rssi);
	        ipNetInfo.put("bssid", bssid);
	        ipNetInfo.put("speed", speed);
	        ipNetInfo.put("networkId", networkId);
	        Log.e("IP-MAC-2",ipNetInfo);
	        return ipNetInfo; 
	    }
	    //信道获取
public static int getCurrentChannel(Context context) 
{
        WifiManager wifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();// 当前wifi连接信息
        ListscanResults = wifiManager.getScanResults();
        for (ScanResult result : scanResults) {
            if (result.BSSID.equalsIgnoreCase(wifiInfo.getBSSID())
                    && result.SSID.equalsIgnoreCase(wifiInfo.getSSID()
                            .substring(1, wifiInfo.getSSID().length() - 1))) {
                return getChannelByFrequency(result.frequency);
            }
        }

        return -1;
    }

    /**
     * 根据频率获得信道
     * 
     * @param frequency
     * @return
     */
    public static int getChannelByFrequency(int frequency) {
        int channel = -1;
        switch (frequency) {
        case 2412:
            channel = 1;
            break;
        case 2417:
            channel = 2;
            break;
        case 2422:
            channel = 3;
            break;
        case 2427:
            channel = 4;
            break;
        case 2432:
            channel = 5;
            break;
        case 2437:
            channel = 6;
            break;
        case 2442:
            channel = 7;
            break;
        case 2447:
            channel = 8;
            break;
        case 2452:
            channel = 9;
            break;
        case 2457:
            channel = 10;
            break;
        case 2462:
            channel = 11;
            break;
        case 2467:
            channel = 12;
            break;
        case 2472:
            channel = 13;
            break;
        case 2484:
            channel = 14;
            break;
        case 5745:
            channel = 149;
            break;
        case 5765:
            channel = 153;
            break;
        case 5785:
            channel = 157;
            break;
        case 5805:
            channel = 161;
            break;
        case 5825:
            channel = 165;
            break;
        }
        return channel;
    }

下面是运行在Android上的效果

Java获取操作系统的本机ip和Mac地址_第1张图片

你可能感兴趣的:(IP地址,mac地址,Android-Mac地址)