可能大家开发时会遇到需要连接电脑的情况,如做一个手机控制电脑的程序。当然,毫无疑问用到Socket编程,进行电脑与手机端的通讯。
当然,这可能要你手动输入IP地址,很麻烦。如何让手机能自动搜索出IP连接电脑呢?
思路一:
电脑服务器端:
package com.net; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; /* *应用场景: 一个学校,每当下课时间到了提供提示下课功能。 */ public class UdpSend { public void sendData() throws SocketException, UnknownHostException { DatagramSocket ds = new DatagramSocket();// 创建用来发送数据报包的套接字 String str = "1"; DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getByName("255.255.255.255"), 3001); // 构造数据报包,用来将长度为 length 的包发送到指定主机上的指定端口号 try { ds.send(dp); } catch (IOException e) { e.printStackTrace(); } ds.close(); } public static void main(String[] args) { Timer timer = new Timer(); timer.schedule(new MyTask(), 1000, 1000); } static class MyTask extends java.util.TimerTask { @Override public void run() { UdpSend tt = new UdpSend(); Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); String strdate = sdf.format(d); String[] classTime = { "17:08:00", "17:19:00", "17:20:00" }; for (int i = 0; i < classTime.length; i++) { if (classTime[i].equals(strdate)) { try { tt.sendData(); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } } } } } }
package com.net; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UdpRecv { public static void main(String[] args) throws Exception { DatagramSocket ds = new DatagramSocket(3001);// 创建接收数据报套接字并将其绑定到本地主机上的指定端口 byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, 1024); ds.receive(dp); String strRecv = new String(dp.getData(), 0, dp.getLength()) + " from " + dp.getAddress().getHostAddress() + ":" + dp.getPort(); System.out.println(strRecv); ds.close(); } }
思路二:
鉴于局域网IP地址已192.168.X.X,可以直接全部遍历。
package com.net; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; public class NetSearcher { public static void main(String[] args) { // TODO code application logic here new NetSearcher(); } public NetSearcher() { long start = System.currentTimeMillis(); Socket socket = new Socket(); byte[] ip = { (byte) 192, (byte) 168, (byte) 0, (byte) 0 }; for (int j = 1; j < 254; j++) { ip[2] = (byte) j; for (int i = 1; i < 254; i++) { try { ip[3] = (byte) i; socket.connect( new InetSocketAddress(InetAddress.getByAddress(ip), 20000), 80); System.out.println("Server's IP 192.168." + j + "." + i); break; } catch (Exception e) { System.out.println("Server IP is not 192.168." + j + "." + i); } } } System.out.println("Time takes " + (System.currentTimeMillis() - start) + " millis."); } }
转载请注明出处:http://blog.csdn.net/xn4545945