Android发现局域网IP

Android发现局域网IP的原理就在于通过udp向路由网关广播消息,然后监听对应的消息回复。示例代码如下:

1、获取udp广播地址

public static InetAddress getBroadcastAddress(Context pContext) throws UnknownHostException {
	    WifiManager cWifi = (WifiManager)pContext.getSystemService(Context.WIFI_SERVICE);
	    DhcpInfo cDhcp = cWifi.getDhcpInfo();
	    if(cDhcp==null) {
	        return InetAddress.getByName("255.255.255.255");
	    }
	    int cBroadcast = (cDhcp.ipAddress & cDhcp.netmask) | ~cDhcp.netmask;
	    byte[] cQuads = new byte[4];
	    for (int k = 0; k < 4; k++)
	    	cQuads[k] = (byte) ((cBroadcast >> k * 8) & 0xFF);
	    return InetAddress.getByAddress(cQuads);
	}

2、根据广播地址创建udp发送和监听机制

public static DatagramSocket mSocket;
public static DatagramPacket mPacket;
public static String startFind(InetAddress cAddr){
		String cIP = "";
		try {
			mSocket = new DatagramSocket(8000);
			mSocket.setBroadcast(true);
			byte[] cBuffer = "Hello World".getBytes();
			DatagramPacket cPacket = new DatagramPacket(cBuffer,cBuffer.length);
			cPacket.setAddress(cAddr);
			cPacket.setPort(9999);
			mSocket.send(cPacket);
			while(true){
				cIP = receiveData();
				if(null != cIP)
					break;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			cIP = null;
		}
		mSocket.close();
		return cIP;
	}
public static String receiveData()
	{
		byte[] cReceivedata = new byte[1024];
		DatagramPacket cPacket = new DatagramPacket(cReceivedata,cReceivedata.length);
		cPacket.getAddress();
		try
		{
			if (mSocket == null){
				Log.e("dataSocket", "null");
			}
			mSocket.receive(cPacket);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
		if(0 != cPacket.getLength()){
			String cCheck = new String(cReceivedata,0,cPacket.getLength());
			Log.i("findIP", cCheck);
			if(cCheck.equals("HelloWorldACK")){
				Log.i("findIP", cPacket.getAddress().getHostAddress());
				return cPacket.getAddress().getHostAddress();
			}
		}
		return null;
	}
注意:在Android中不能在app主线程中进行socket资源的动作,至于原因,相信会android的人都知道

你可能感兴趣的:(Android编程)