2016-10-22 4 views
-2
Socket socket = new Socket(); 

try { 
Process process = Runtime.getRuntime().exec("arp -i en0 -a -n"); 
process.waitFor(); 
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 

while (reader.ready()) { 
    String ip = reader.readLine(); 
    ip = ip.substring(3, ip.indexOf(')')); 

    try { 
     socket.connect(new InetSocketAddress(ip, 1234), 1000); 
     System.out.println("Found socket!"); 
    } catch (ConnectException | SocketTimeoutException ignored) { 

    } 
} 

if (socket == null) { 
    System.err.println("Could not find socket."); 
} 
} catch (Exception e) { 
e.printStackTrace(); 
} 

이 코드는 Mac에서 찾을 수 있으며 Windows 용 대안을 찾아야합니다. 그것이 내가 Windows에서 사용되는 ARP (Address Resolution Protocol)에 대한 -i 매개 변수가 믿지 않는로 시작하는 예외특정 포트 번호가 열려있는 네트워크상의 모든 장치의 IP 주소를 찾으십시오.

+0

당신이 어떤 연구를하고 어딘가에 붙어 쪘 :

여기에 새로운 예는 위의 모든 기재 사항을 보여주는 실행 가능한입니까? 오류 메시지를 공유하고 여기서 질문하기 전에 문제를 진단하기 위해 취한 디버깅 단계를 알려주십시오. – 4castle

+0

내가 시도 BT coudn't –

+0

java.lang.StringIndexOutOfBoundsException 그것을 알아낼 : 문자열 색인이 범위를 벗어 : -4 java.lang.String.substring에서 \t (String.java:1967) \t javaapplication21.JavaApplication21.main에서을 (JavaApplication21.java:66) –

답변

1

음을 제공합니다 창에 . -n 매개 변수가 있지만 -N 인 반면 N은 대문자입니다. ARP 명령 줄이 잘못되어 Windows 명령 프롬프트 창을 사용하여 직접 확인해야합니다. 명령 프롬프트 창에 arp을 입력하면 ARP에 사용할 수있는 모든 매개 변수를 볼 수 있습니다.

제공 할 ARP 테이블을 검색하려면 "arp -a"하지만 거래 한 것 이상을 받게되며 연결된 장치에 필요한 IP 주소를 파싱해야합니다 나는 Dynamic IP라고 생각한다. 여기에 윈도우 10 상자에서 ARP 테이블의 예입니다

Interface: 192.168.0.25 --- 0x2 
    Internet Address  Physical Address  Type 
    192.168.0.69   25-ad-42-bb-bd-65  dynamic 
    192.168.0.254   b8-29-34-f9-27-65  dynamic 
    192.168.0.255   ff-ff-ff-ff-ff-ff  static 
    224.0.0.2    01-00-5e-00-00-02  static 
    224.0.0.22   01-00-5e-00-00-16  static 
    224.0.0.251   01-00-5e-00-00-fb  static 
    224.0.0.252   01-00-5e-00-00-fc  static 
    224.0.0.253   01-00-5e-00-00-fd  static 
    239.255.255.250  01-00-5e-7f-ff-fa  static 
    239.255.255.253  01-00-5e-7f-ff-fd  static 
    255.255.255.255  ff-ff-ff-ff-ff-ff  static 

앞에서 언급 한 바와 같이, 나는 당신이 동적 IP 주소입니다 원하는 것을 생각하지만, 당신이 그것을 구문 분석하는 당신에게 달려있을 것입니다 원하는 무엇이든 데이터를 정리하십시오. 원하는 데이터를 파싱 할 때는 목록 Array에 배치하는 것이 좋습니다. 아래는 귀하의 Windows 컴퓨터에서 작동해야합니다 작은 runnable을 제공합니다 :

package networkdevices; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.ConnectException; 
import java.net.InetSocketAddress; 
import java.net.Socket; 
import java.net.SocketTimeoutException; 
import java.util.ArrayList; 
import java.util.List; 


public class NetworkDevices { 
    private static int port = 1234; 

    public static void main(String[] args) { 
     getNetworkDevices(); 
    } 

    private static void getNetworkDevices(){ 
     Socket socket = new Socket(); 

     try { 
      Process process = Runtime.getRuntime().exec("arp -a"); 
      process.waitFor(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 

      String ip = null; 
      List<String> ipList = new ArrayList<>(); // List<> Array to hold dynamic IP Addresses 
      while ((ip = reader.readLine()) != null) { 
       ip = ip.trim();  // Trim the data 
       if (!ip.equals("")) { 
        if (!ip.equals("")) { 
         // Remove all the unwanted spaces between data provided by 
         // the ARP Table when it is generated. 
         while (ip.contains(" ")) { ip = ip.trim().replace(" ", " "); } 
         // Split each data line into a String Array for processing 
         String[] dataArray = ip.split(" "); 
         // For console output display only... 
         if (dataArray[0].toLowerCase().startsWith("interface:")) { 
          System.out.println("Locating Devices Connected To: " + dataArray[1]); 
         } 
         // If the data line contains the word "dynamic" 
         // then add the IP address on that line to the 
         // List<> Array... 
         if (dataArray[2].equalsIgnoreCase("dynamic")) { 
          ipList.add(dataArray[0]); 
          // For console output display only... 
          System.out.println("Device Located On IP: " + dataArray[0]); 
         } 
        } 
       } 
      } 
      // Close the Reader 
      reader.close(); 

      // try to connect to the device.... 
      // You'll need to play with this. 
      try { 
       for (int i = 0; i < ipList.size(); i++) { 
        ip = ipList.get(i); 
        socket.connect(new InetSocketAddress(ip, port), 1000); 
        if (socket == null) { 
         System.err.println("Could not find socket."); 
        } 
        else { 
         System.out.println("Found socket for: " + ip); 
        } 
        socket.close(); 
       } 
      } catch (ConnectException | SocketTimeoutException ex) { 
       System.out.println("\nSOCKET ERROR - " + ex.getMessage()); 
      } 
     } catch (IOException | InterruptedException e) { 
      System.out.println("\nPROCESS/READER ERROR - " + e.getMessage()); 
     } 
    } 
} 
+0

매번 소켓 시간 초과 예외가 있습니다. 당신이 그 해결책을 제공 할 수 있다면 그것은 위대 할 것입니다. –

+0

@Aviral Ahuja, 2 차 답변을보십시오. 나는 이것이 당신을 위해 몇 가지를 정리하기를 바랍니다. – DevilsHnd

0

이 추가 답변은 소켓 연결에 관한 두 번째 질문입니다. 이것은 다른 주제로 시작되었지만 덜 절대로 시작하지 않아야합니다 ....

불행히도 소켓 객체를 플러시하고 발견 된 장치에 연결할 것으로 예상하는 것처럼 간단하지 않습니다. 방화벽 보호, 안티 바이러스 보호, 포트 번호와 같은 장치 자체의 연결 요구 사항 등과 같이 각 장치에 대해 고려해야 할 사항이 몇 가지 있습니다. 또한 80과 같은 공통 포트를 사용하여 더 많은 성공을 거둘 수 있습니다

제 의견으로는 소켓 연결이 좀 더 견고 해져서 연결이 실패하거나 성공할 수있는 이유에 대한 승인을받을 수 있어야합니다. 사실상 (IMO) 소켓 연결은 다른 방법으로 수행되어야합니다.

또 다른 실행 가능한 예제를 제공하지만 이번에는 몇 가지 변경을 수행하고 몇 가지 방법을 추가했습니다. 내가 만든 첫 번째 변화는 내가 getNetworkDevices() getNetworkDeviceIPs()- 방법을 이름을 변경하고 실제로> 문자열 목록 <을 반환 감지 장치 IP의의 배열이있다이었다. 두 번째 변경 사항은 소켓 연결 코드를 getNetworkDeviceIPs() 메쏘드에서 제거하고 소켓 연결 코드를 이라는 다른 메쏘드 connectToDevices()에 넣었다는 것입니다.

앞서 언급했듯이 아래에 표시된 새로운 실행 가능 예제에 몇 가지 새로운 메소드를 추가했습니다.첫 번째 메서드는 getDeviceName()이며이 메서드는 getNetworkDeviceIPs() 메서드에서 가져온 List <> Array의 IP 주소를 전달합니다. List <> Array의 요소에 포함 된 각 IP는 콘솔에서 해당 장치의 호스트 이름 (IP 주소와 함께)을 표시하도록이 방법을 통해 반복되고 검사됩니다.

두 번째 새로운 방법이 (우리가 이전에 접촉으로) connectToDevices라는() 목록 <>는 getNetworkDeviceIPs에서 검색 어레이() 방법을 전달. 이 메서드는 문자열 목록 <> 배열 내에 포함 된 각 장치 IP 주소에 소켓 연결을 시도합니다. 이 메소드는 현재 아무것도 반환하지 않으며 (void) 성공했는지 여부에 대한 콘솔 창에 연결 결과를 표시합니다. 물론이 방법을 수정하여 원하는 결과를 반환 할 수 있습니다.

package networkdevices; 

import java.io.BufferedReader; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.net.InetAddress; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import java.util.ArrayList; 
import java.util.List; 


public class NetworkDevices { 
    public static int port = 80; 

    public static void main(String[] args) { 
     //Get devices from system ARP Table and 
     // place their IP's into a List<> Array... 
     List<String> ipList = getNetworkDeviceIPs(port); 

     // Iterate trough the List<> Array and display 
     // Device names stored within with the getDeviceName() 
     // method... 
     System.out.println("\nListing Device Names - Please Wait..."); 
     for (int i = 0; i < ipList.size(); i++) { 
      System.out.println(getDeviceName(ipList.get(i))); 
     } 

     // Try to connect to each Device that is storred 
     // within the List<> Array.... 
     System.out.println("\nTrying To Connect To Devices..."); 
     connectToDevices(ipList, port); 
    } 

    private static List<String> getNetworkDeviceIPs(int portNumber){ 
     Socket socket = new Socket(); 
     List<String> ipList = new ArrayList<>(); // List<> Array to hold IP Addresses 

     try { 
      Process process = Runtime.getRuntime().exec("arp -a"); 
      process.waitFor(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 

      String ip = null; 
      while ((ip = reader.readLine()) != null) { 
       ip = ip.trim();  // Trim the data 
       if (!ip.equals("")) { 
        if (!ip.equals("")) { 
         // Remove all the unwanted spaces between data provided by 
         // the ARP Table when it is generated. 
         while (ip.contains(" ")) { ip = ip.trim().replace(" ", " "); } 
         // Split each data line into a String Array for processing 
         String[] dataArray = ip.split(" "); 
         // For console output display only... 
         if (dataArray[0].toLowerCase().startsWith("interface:")) { 
          System.out.println("Locating Devices Connected To: " + dataArray[1]); 
         } 
         // If the data line contains the word "dynamic" 
         // then add the IP address on that line to the 
         // List<> Array... 
         if (dataArray[2].equalsIgnoreCase("dynamic")) { 
          ipList.add(dataArray[0]); 
          // For console output display only... 
          System.out.println("Device Located On IP: " + dataArray[0]); 
         } 
        } 
       } 
      } 
      // Close the Reader 
      reader.close(); 
     } 
     catch (IOException | InterruptedException e) { 
      System.out.println("\nPROCESS/READER ERROR - " + e.getMessage()); 
     } 
     return ipList; 
    } 

    private static String getDeviceName(String localIP) { 
     String result = ""; 
     try { 
      InetAddress address = InetAddress.getByName(localIP); 
      if (address.isReachable(500)) { 
       // Device is turned on and can be pinged!; 
       result = address.toString(); 
      } 
      else if (!address.getHostAddress().equals(address.getHostName())) { 
       // Device is identified in a DNS lookup! 
       result = address.toString(); 
      } 
      else { 
       // if you keep getting something like "Unknown Device!/192.168.0.5 then the host 
       // address and host name are the same, meaning the host name could not be resolved. 
       // This means that either your router just isn't storing the information OR those 
       // devices just choose not to submit their host name to the router, and that is why 
       // you will continually get this message. Apparently, there is no way around this 
       // because those device names literally aren't stored anywhere. 
       result = "Unknown Device!/" + address.toString().substring(0,address.toString().indexOf("/")); 
      } 
     } 
     catch (UnknownHostException ex) { System.out.println(ex.getMessage()); } 
     catch (IOException ex) { System.out.println(ex.getMessage()); } 

     return result; 
    } 

    private static void connectToDevices(List<String> localIPAddresses, int port) { 
     // try to connect to the device(s).... 
     // You'll need to play with this. 
     for (int i = 0; i < localIPAddresses.size(); i++) { 
      if (i > 0) { System.out.println(""); } 
      try { 
       System.out.println("Connecting to: " + localIPAddresses.get(i) + " on port: " + 
            port + " - Please Wait..."); 
       Socket thisSystem = new Socket(localIPAddresses.get(i), port); 

       System.out.println("Just connected to: " + thisSystem.getRemoteSocketAddress()); 
       OutputStream outToServer = thisSystem.getOutputStream(); 
       DataOutputStream out = new DataOutputStream(outToServer); 

       out.writeUTF("Hello from: " + thisSystem.getLocalSocketAddress()); 
       InputStream inFromServer = thisSystem.getInputStream(); 
       DataInputStream in = new DataInputStream(inFromServer); 

       System.out.println("Device says " + in.readUTF()); 
       thisSystem.close(); 
      } 
      catch(IOException e) { System.out.println(e.getLocalizedMessage()); } 
     } 
    } 
} 
관련 문제