简体   繁体   中英

Find out which port a USB connection is coming from

I need to have a program that detects which USB port flash drives are plugged into. I can find if a certain drive is connected or not, but not where it is.

For Example, when Drive 1 gets connected to USB port 1, I need to be able to say Drive 1 connected to Port 1. Is there anyway to do this in Java, C#, c++, c or any other language. I am comfortable with any of those languages.

Here is what I had with Java. This tells me when Drive D, or Drive F is connected but not in what port. Thanks in advance for any help.

public class FindDrive
{

public static void main(String[] args)
{
String[] letters = new String[]{ "A", "B", "C", "D", "E", "F", "G", "H", "I"};
File[] drives = new File[letters.length];
boolean[] isDrive = new boolean[letters.length];

// init the file objects and the initial drive state
for ( int i = 0; i < letters.length; ++i )
    {
    drives[i] = new File(letters[i]+":/");

    isDrive[i] = drives[i].canRead();
    }

 System.out.println("FindDrive: waiting for devices...");

 // loop indefinitely
 while(true)
    {
    // check each drive 
    for ( int i = 0; i < letters.length; ++i )
        {
        boolean pluggedIn = drives[i].canRead();

        // if the state has changed output a message
        if ( pluggedIn != isDrive[i] )
            {
            if ( pluggedIn )
                System.out.println("Drive "+letters[i]+" has been plugged in");
            else
                System.out.println("Drive "+letters[i]+" has been unplugged");

            isDrive[i] = pluggedIn;
            }
        }

    // wait before looping
    try { Thread.sleep(100); }
    catch (InterruptedException e) { /* do nothing */ }

    }
}
}

If I was not clear enough, please let me know. I really need to find the solution to this.

Looks like usb4java can do what you want. Look at the high-level API , specifically the USBDevice#getParentPort() method.

Here's some example code to get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM