Android/Linux检测网线是否插入

http://blog.csdn.net/u013686019/article/details/52335441

有很多方式可以获取网线插入与否的状态,最简单的方式莫过于查询内核通过VS暴漏给用户的信息。

1、cat /sys/class/net/eth0/carrier
1
如果插有网线的话,读取到的值是1,否则为0


Java代码参考:

private int getEthernetCarrierState(String iface) {
	if(iface != "") {
		try {
			File file = new File("/sys/class/net/"+iface+"/carrier");
			String carrier = ReadFromFile(file);
			int carrier_state = Integer.parseInt(carrier);
			return carrier_state;
		} catch(Exception e) {
			e.printStackTrace();
			return 0;
		}
	} else {
		return 0;
	}
}

2、cat /proc/net/dev
Inter-|   Receive                                                |  Transmit
 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
  eth0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0
 wlan0:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0
    lo: 3878205   51627    0    0    0     0          0         0  3878205   51627    0    0    0     0       0          0

如果插入网线的话,eth0接口对应的bytes、packets肯定不为0。


Java代码参考:

private boolean isWirePluggedIn() {
	final String fileName = "/proc/net/dev";
	File file = new File(fileName);
	if (!file.exists()) {
		Log.e(TAG, "file not exists");
		return false;
	}

	try {
		BufferedReader reader = null;
		reader = new BufferedReader(new FileReader(file));
		String line = null;
		while ((line = reader.readLine()) != null) {
			if (line.contains("eth0:")) {
				break;
			}
		}

		if (line.contains("eth0:")) {
			StringTokenizer tokenizer = new StringTokenizer(line);
			tokenizer.nextToken();
			final String ethBytes = tokenizer.nextToken();
			reader.close();
			return Integer.parseInt(ethBytes) > 0;
		}

		reader.close();
		return false;
	} catch (FileNotFoundException e) {
		Log.e(TAG, "FileNotFoundException");
	} catch (IOException e) {
		Log.e(TAG, "IOException: " + e.getLocalizedMessage());
	}

	return false;
}

你可能感兴趣的:(Android源码,Linux网络)