이 추가 답변은 소켓 연결에 관한 두 번째 질문입니다. 이것은 다른 주제로 시작되었지만 덜 절대로 시작하지 않아야합니다 ....
불행히도 소켓 객체를 플러시하고 발견 된 장치에 연결할 것으로 예상하는 것처럼 간단하지 않습니다. 방화벽 보호, 안티 바이러스 보호, 포트 번호와 같은 장치 자체의 연결 요구 사항 등과 같이 각 장치에 대해 고려해야 할 사항이 몇 가지 있습니다. 또한 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()); }
}
}
}
당신이 어떤 연구를하고 어딘가에 붙어 쪘 :
여기에 새로운 예는 위의 모든 기재 사항을 보여주는 실행 가능한입니까? 오류 메시지를 공유하고 여기서 질문하기 전에 문제를 진단하기 위해 취한 디버깅 단계를 알려주십시오. – 4castle
내가 시도 BT coudn't –
java.lang.StringIndexOutOfBoundsException 그것을 알아낼 : 문자열 색인이 범위를 벗어 : -4 java.lang.String.substring에서 \t (String.java:1967) \t javaapplication21.JavaApplication21.main에서을 (JavaApplication21.java:66) –