不使用applet和active控件实现java获取客户单ip地址和mac地址

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class getMacAddrServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("客户单的ip地址是:");
		System.out.println(req.getRemoteAddr());

		//注意此处的获取的mac地址可能不是正确的mac地址,因为可能存在无线网卡和虚拟机的网卡
		//而方法getMACAddress是可以获取到所有的mac地址的,至于具体是那个网卡的mac地址需要自己在判断,详见方法getMACAddress
		System.out.println("客户端的mac地址是:");
		System.out.println(this.getMACAddress(req.getRemoteAddr()));
		super.doPost(req, resp);
	}

	public String getMACAddress(String ip) {
		String str = "";
		String macAddress = "";
		try {
			Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
			InputStreamReader ir = new InputStreamReader(p.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			for (int i = 1; i < 100; i++) {
				str = input.readLine();
				if (str != null) {
					if (str.indexOf("MAC Address") > 1) {
						macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
						break;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace(System.out);
		}
		return macAddress;
	}
}

你可能感兴趣的:(java,虚拟机,servlet)