Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>On my laptop (running Windows 7, with Virtual Box and it's network interface installed) the following code prints out the name of my wireless interface along with my local address. It uses a brute force approach at the end of the day, but will only try and actually connect to addresses that are considered to be the best candidates.</p> <pre><code>// iterate over the network interfaces known to java Enumeration&lt;NetworkInterface&gt; interfaces = NetworkInterface.getNetworkInterfaces(); OUTER : for (NetworkInterface interface_ : Collections.list(interfaces)) { // we shouldn't care about loopback addresses if (interface_.isLoopback()) continue; // if you don't expect the interface to be up you can skip this // though it would question the usability of the rest of the code if (!interface_.isUp()) continue; // iterate over the addresses associated with the interface Enumeration&lt;InetAddress&gt; addresses = interface_.getInetAddresses(); for (InetAddress address : Collections.list(addresses)) { // look only for ipv4 addresses if (address instanceof Inet6Address) continue; // use a timeout big enough for your needs if (!address.isReachable(3000)) continue; // java 7's try-with-resources statement, so that // we close the socket immediately after use try (SocketChannel socket = SocketChannel.open()) { // again, use a big enough timeout socket.socket().setSoTimeout(3000); // bind the socket to your local interface socket.bind(new InetSocketAddress(address, 8080)); // try to connect to *somewhere* socket.connect(new InetSocketAddress("google.com", 80)); } catch (IOException ex) { ex.printStackTrace(); continue; } System.out.format("ni: %s, ia: %s\n", interface_, address); // stops at the first *working* solution break OUTER; } } </code></pre> <p><sub>(I've updated my answer with <code>isReachable(...)</code> based on <a href="https://stackoverflow.com/users/383688/mockertim">Mocker Tim's</a> answer.)</sub></p> <p>One thing to watch out for. <code>socket.bind(...)</code> would bark at me that the address and port is already in use if I tried to run my code too fast in succession like the connection isn't cleaned up fast enough. <code>8080</code> should be a random port maybe.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload