局域网内获取周围设备的ip和端口

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/mikejaps/article/details/49507067

 欢迎大家访问我的博客http://blog.csdn.net/mikejaps专注于android ios  app 开发     


  现在智能家居,物联网非常火,推进了WiFi模块的使用,出货量大为增加。据了解,现在大部分WiFi模块在第一次配置的时候是采用udp广播的方式来通讯的,手机端将路由的名称和密码通过udp 广播的方式发送给WiFi模块,这样的方式适合远程控制,在和WiFi模块近距离通讯的时候如果WiFi模块已经连上了路由,我们如何获取WiFi模块的ip,和 端口呢?下面介绍mdns协议--发现周围设备的ip和端口。

关键代码:

<pre name="code" class="java">public class DnsService extends Service implements ServiceListener,
		ServiceTypeListener {

	/**
	 * 日志标签
	 */
	private static final String TAG = "DnsService";

	/**
	 * Instance of Bonjour/Rendezvous/ZeroConf handler
	 */
	public JmDNS jmdns = null;

	/**
	 * Allows an application to receive Wifi Multicast packets.
	 */
	private MulticastLock multicastLock = null;

	private SocketBinder mBinder = new SocketBinder();

	private Handler handler;

	private List<Map<String, String>> ipList = new ArrayList<Map<String, String>>();

	public class SocketBinder extends Binder {
		public DnsService getService() {
			return DnsService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		startScan();
		return mBinder;
	}

	public void setMessageHandler(Handler h) {
		handler = h;
	}

	@Override
	public void onDestroy() {
		stopScan();
		super.onDestroy();
	}

	/**
	 * 添加完service后
	 */
	@Override
	public void serviceAdded(ServiceEvent event) {
		jmdns.getServiceInfo(event.getType(), event.getName());
		// jmdns.removeServiceTypeListener(DnsService.this);
		// JmdnsHandler.removeMessages(2000);
		// JmdnsHandler.sendEmptyMessageDelayed(2000, 5000);
	}

	/**
	 * Delegate method from mDNS when a service is removed.
	 */
	@Override
	public void serviceRemoved(ServiceEvent event) {

	}

	@SuppressLint("HandlerLeak")
	private Handler JmdnsHandler = new Handler() {
		public void handleMessage(Message msg) {
			Log.d(TAG, "serviceRemoved");
			if (jmdns == null)
				return;
			stopScan();
			startScan();
			// jmdns.unregisterAllServices();
			// // jmdns.removeServiceTypeListener(DnsService.this);
			// try {
			// jmdns.addServiceTypeListener(DnsService.this);
			// } catch (IOException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
		};
	};

	/**
	 * Delegate method from mDNS when a service is resolved.
	 */
	@Override
	public void serviceResolved(ServiceEvent event) {
		ServiceInfo info = event.getInfo();
		// Log.d(TAG, event.getInfo().getPropertyString("vendor"));
		Log.d(TAG, event.getInfo().getNiceTextString());

		boolean isChanged = false;
		for (int i = 0; i < info.getInet4Addresses().length; i++) {
			if (!ipList.contains(info.getInet4Addresses()[i].toString()
					.substring(1))) {

				Map<String, String> map = new HashMap<String, String>();
				map.put(info.getInet4Addresses()[i].toString().substring(1),
						event.getInfo().getName());
				ipList.add(map);
				isChanged = true;
				map = null;
			}
		}
		if (isChanged) {
			Message msg = handler.obtainMessage();
			msg.obj = ipList;
			msg.arg1 = event.getInfo().getPort();
			handler.sendMessage(msg);
		}

	}

	/**
	 * 发现服务并添加
	 */
	@Override
	public void serviceTypeAdded(ServiceEvent event) {
		if (event.getType().contains("Light"))
			jmdns.addServiceListener(event.getType(), this);

	}

	/**
	 * Delegate method from mDNS when a subtype is discovered.
	 */
	@Override
	public void subTypeForServiceTypeAdded(ServiceEvent event) {

	}

	private Thread thread;

	public void startScan() {
		thread = null;
		thread = new Thread() {
			@Override
			public void run() {
				try {
					Log.i(TAG, "开始搜索...");
					try {
						sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					jmdns = JmDNS.create();
					jmdns.addServiceTypeListener(DnsService.this);

				} catch (IOException ex) {
					Log.e(TAG, "开始搜索...fail");
				}
			}
		};
		thread.start();
		JmdnsHandler.removeMessages(2000);
		JmdnsHandler.sendEmptyMessageDelayed(2000, 10000);
	}

	/**
	 * 停止搜索
	 */
	public void stopScan() {
		JmdnsHandler.removeMessages(2000);

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					if (jmdns != null) {
						Log.i(TAG, "Stopping ZeroConf probe....");
						jmdns.unregisterAllServices();
						jmdns.close();
						jmdns = null;
					}
					if (multicastLock != null) {
						Log.i(TAG, "Releasing Mutlicast Lock...");
						multicastLock.release();
						multicastLock = null;
					}
				} catch (Exception ex) {
					Log.e(TAG, ex.getMessage(), ex);
				}
			}
		}).start();

	}

}


jar包下载地址 点击打开链接 http://download.csdn.net/detail/mikejaps/9225799


展开阅读全文

没有更多推荐了,返回首页