Android:手機掃描局域網所有ip,並進行socket通訊

Android手機局域網掃描PC機,利用android的ping命令掃描局域網內所有ip,並對其進行socket通信
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import org.apache.http.conn.util.InetAddressUtils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
 
public class NetTool {
   
   
  private int SERVERPORT = 8888;
   
  private String locAddress;//存儲本機ip,例:本地ip :192.168.1.
   
  private Runtime run = Runtime.getRuntime();//獲取當前運行環境,來執行ping,相當於windows的cmd
   
  private Process proc = null;
   
  private String ping = "ping -c 1 -w 0.5 " ;//其中 -c 1爲發送的次數,-w 表示發送後等待響應的時間
   
  private int j;//存放ip最後一位地址 0-255
   
  private Context ctx;//上下文
   
  public NetTool(Context ctx){
    this.ctx = ctx;
  }
 
 
 
  private Handler handler = new Handler(){
     
    public void dispatchMessage(Message msg) {
      switch (msg.what) {
       
      case 222:// 服務器消息
        break;
         
      case 333:// 掃描完畢消息
        Toast.makeText(ctx, "掃描到主機:"+((String)msg.obj).substring(6), Toast.LENGTH_LONG).show();
         
        break;
      case 444://掃描失敗
        Toast.makeText(ctx, (String)msg.obj, Toast.LENGTH_LONG).show();
        break;
      }
    }
 
  };
   
 
 
  //向serversocket發送消息
  public String sendMsg(String ip,String msg) {
     
    String res = null;
    Socket socket = null;
     
    try {
      socket = new Socket(ip, SERVERPORT);
      //向服務器發送消息
      PrintWriter os = new PrintWriter(socket.getOutputStream());
      os.println(msg);
      os.flush();// 刷新輸出流,使Server馬上收到該字符串
       
      //從服務器獲取返回消息
      DataInputStream input = new DataInputStream(socket.getInputStream());  
      res = input.readUTF();
      System.out.println("server 返回信息:" + res);
      Message.obtain(handler, 222, res).sendToTarget();//發送服務器返回消息
 
    } catch (Exception unknownHost) {
      System.out.println("You are trying to connect to an unknown host!");
    } finally {
      // 4: Closing connection
      try {
        if (socket != null) {
          socket.close();
        }
      } catch (IOException ioException) {
        ioException.printStackTrace();
      }
    }
    return res;
  }
   
 
 
  /**
   * 掃描局域網內ip,找到對應服務器
   */
  public void scan(){
     
    locAddress = getLocAddrIndex();//獲取本地ip前綴
     
    if(locAddress.equals("")){
      Toast.makeText(ctx, "掃描失敗,請檢查wifi網絡", Toast.LENGTH_LONG).show();
      return ;
    }
     
    for ( int i = 0; i < 256; i++) {//創建256個線程分別去ping
       
      j = i ;
       
      new Thread(new Runnable() {
         
        public void run() {
           
          String p = NetTool.this.ping + locAddress + NetTool.this.j ;
           
          String current_ip = locAddress+ NetTool.this.j;
           
          try {
            proc = run.exec(p);
             
            int result = proc.waitFor();
            if (result == 0) {
              System.out.println("連接成功" + current_ip);
              // 向服務器發送驗證信息
              String msg = sendMsg(current_ip,"scan"+getLocAddress()+" ( "+android.os.Build.MODEL+" ) ");
               
              //如果驗證通過...
              if (msg != null){
                if (msg.contains("OK")){
                  System.out.println("服務器IP:" + msg.substring(8,msg.length()));
                  Message.obtain(handler, 333, msg.substring(2,msg.length())).sendToTarget();//返回掃描完畢消息
                }
              }
            } else {
               
            }
          } catch (IOException e1) {
            e1.printStackTrace();
          } catch (InterruptedException e2) {
            e2.printStackTrace();
          } finally {
            proc.destroy();
          }
        }
      }).start();
       
    }
     
  }
 
   
  //獲取本地ip地址
  public String getLocAddress(){
     
    String ipaddress = "";
     
    try {
      Enumeration<networkinterface> en = NetworkInterface.getNetworkInterfaces();
      // 遍歷所用的網絡接口
      while (en.hasMoreElements()) {
        NetworkInterface networks = en.nextElement();
        // 得到每一個網絡接口綁定的所有ip
        Enumeration<inetaddress> address = networks.getInetAddresses();
        // 遍歷每一個接口綁定的所有ip
        while (address.hasMoreElements()) {
          InetAddress ip = address.nextElement();
          if (!ip.isLoopbackAddress()
              && InetAddressUtils.isIPv4Address(ip.getHostAddress())) {
            ipaddress = ip.getHostAddress();
          }
        }
      }
    } catch (SocketException e) {
      Log.e("", "獲取本地ip地址失敗");
      e.printStackTrace();
    }
     
    System.out.println("本機IP:" + ipaddress);
     
    return ipaddress;
 
  }
   
  //獲取IP前綴
  public String getLocAddrIndex(){
     
    String str = getLocAddress();
     
    if(!str.equals("")){
      return str.substring(0,str.lastIndexOf(".")+1);
    }
     
    return null;
  }
   
  //獲取本機設備名稱
  public String getLocDeviceName() {
     
    return android.os.Build.MODEL;
     
  }
   
   
}
 
</inetaddress>
</networkinterface>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章