Solved

Create a UUID without JNI

Posted on 2002-05-30
15
473 Views
Last Modified: 2008-02-01
howto?
0
Comment
Question by:egono
  • 6
  • 4
  • 2
  • +2
15 Comments
 
LVL 35

Expert Comment

by:girionis
ID: 7044478
 Take a look here: http://www.jguru.com/faq/view.jsp?EID=261286 it might come in handy.

  Hope it helps.
0
 
LVL 2

Author Comment

by:egono
ID: 7044502
thanks - but I said: "without JNI"

I already know this one http://www.jguru.com/forums/view.jsp?EID=707121 but I'm not sure if it's free.
0
 
LVL 35

Expert Comment

by:girionis
ID: 7044530
 Oops.. Sorry, I thought you said with. Sorry again.
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 2

Author Comment

by:egono
ID: 7044610
no problem :-)

in the meantime I've found http://www.doomdark.org/doomdark/proj/jug/index.html

the only downside is, that it uses a faked ethernet address, but it seems to be impossible to get the mac address without JNI

0
 
LVL 35

Expert Comment

by:girionis
ID: 7044709
 Why would you not want to use JNI?
0
 
LVL 2

Author Comment

by:egono
ID: 7044829
it should run on several platforms (mainly win and linux) and I may get it work on windows but I have absolutely no clue about linux :-(
0
 
LVL 3

Expert Comment

by:cwrea
ID: 7045099
For what do you need a UUID?
0
 
LVL 5

Expert Comment

by:fontaine
ID: 7045115
What about using the ObjID class of java.rmi.server? From the Javadoc:

"The ObjID() constructor can be used to generate a unique object identifier. Such an ObjID is unique over time with respect to the host it is generated on."

This is pure Java (JDK 1.1).
0
 
LVL 3

Expert Comment

by:cwrea
ID: 7045117
From an expired Internet draft:

----- 8< snip 8< -----
4. Node IDs when no IEEE 802 network card is available

  If a system wants to generate UUIDs but has no IEE 802 compliant
  network card or other source of IEEE 802 addresses, then this section
  describes how to generate one.

  The ideal solution is to obtain a 47 bit cryptographic quality random
  number, and use it as the low 47 bits of the node ID, with the most
  significant bit of the first octet of the node ID set to 1. This bit
  is the unicast/multicast bit, which will never be set in IEEE 802
  addresses obtained from network cards; hence, there can never be a
  conflict between UUIDs generated by machines with and without network
  cards.
----- 8< snip 8< -----

You'll find the whole draft at http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt, which describes the format of UUIDs in detail.

Note that getting the host's real MAC address from Java will likely require JNI or running an external program.  I've seen in some reference material that it may also be possible if the host is running an SNMP agent, which can be queried.

I suggest you create your GUID using whatever way is best on your primary target platforms, and then use the above method as a fallback.

0
 
LVL 19

Accepted Solution

by:
Jim Cakalic earned 200 total points
ID: 7045136
Chapter 5 of the EJB Design Patterns book contains a discussion and implementation of UUID for an EJB context -- although it doesn't conform to the definition of UUID in the Network Working Group Internet Draft because the algorithms defined in that document do not work in an EJB environment. Still, if you are looking for a way to generate an identity which is unique across all machines in a cluster, across all UUID generators within a JVM, and down to method call within millisecond, then this might work for you.
    http://www.theserverside.com/books/EJBDesignPatterns/index.jsp

If you _really_ want the MAC address, a possible solution was posted to the Java Developer Connection Forum that, given several constraints, may work for you. Here it is:

---------- NetworkInfo.java ----------
/** try to determine MAC address of local network card; this is done
    using a shell to run ifconfig (linux) or ipconfig (windows). The
    output of the processes will be parsed.
    <p>To run the whole thing, just type java NetworkInfo
    <p>Current restrictions:
    <ul>
    <li>Will probably not run in applets
    <li>Tested Windows / Linux only
    <li>Tested J2SDK 1.4 only
    <li>If a computer has more than one network adapters, only
        one MAC address will be returned
    <li>will not run if user does not have permissions to run
        ifconfig/ipconfig (e.g. under linux this is typically
        only permitted for root)
    </ul>
*/
import java.net.InetAddress;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.StringTokenizer;

public final class NetworkInfo {
    private final static String getMacAddress() throws IOException {
        String os = System.getProperty("os.name");
        try {
            if (os.startsWith("Windows")) {
                return windowsParseMacAddress(windowsRunIpConfigCommand());
            } else if (os.startsWith("Linux")) {
                return linuxParseMacAddress(linuxRunIfConfigCommand());
            } else {
                throw new IOException("unknown operating system: " + os);
            }
        } catch (ParseException ex) {
            ex.printStackTrace();
            throw new IOException(ex.getMessage());
        }
    }  

    /*
     * Linux stuff
     */
    private final static String linuxParseMacAddress(String ipConfigResponse) throws ParseException {
        String localHost = null;
        try {
            localHost = InetAddress.getLocalHost().getHostAddress();
        } catch (java.net.UnknownHostException ex) {
            ex.printStackTrace();
            throw new ParseException(ex.getMessage(), 0);
        }
        StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");        
        String lastMacAddress = null;      
        while (tokenizer.hasMoreTokens()) {
            String line = tokenizer.nextToken().trim();
            boolean containsLocalHost = line.indexOf(localHost) >= 0;          
            // see if line contains IP address      
            if (containsLocalHost && lastMacAddress != null) {
                return lastMacAddress;
            }
            // see if line contains MAC address
            int macAddressPosition = line.indexOf("HWaddr");
            if (macAddressPosition <= 0)
                continue;
            String macAddressCandidate = line.substring(macAddressPosition + 6).trim();
            if (linuxIsMacAddress(macAddressCandidate)) {
                lastMacAddress = macAddressCandidate;
                continue;
            }
        }
        ParseException ex = new ParseException("cannot read MAC address for " + localHost + " from [" + ipConfigResponse + "]", 0);
        ex.printStackTrace();
        throw ex;
    }
    private final static boolean linuxIsMacAddress(String macAddressCandidate) {
        // TODO: use a smart regular expression
        if (macAddressCandidate.length() != 17)
            return false;
        return true;
    }
    private final static String linuxRunIfConfigCommand() throws IOException {
        Process p = Runtime.getRuntime().exec("ifconfig");
        InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
        StringBuffer buffer= new StringBuffer();
        for (;;) {
            int c = stdoutStream.read();
            if (c == -1)
                break;
            buffer.append((char)c);
        }
        String outputText = buffer.toString();
        stdoutStream.close();
        return outputText;
    }

    /*
     * Windows stuff
     */
    private final static String windowsParseMacAddress(String ipConfigResponse) throws ParseException {
        String localHost = null;
        try {
            localHost = InetAddress.getLocalHost().getHostAddress();
        } catch (java.net.UnknownHostException ex) {
            ex.printStackTrace();
            throw new ParseException(ex.getMessage(), 0);
        }
        StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
        String lastMacAddress = null;
        while (tokenizer.hasMoreTokens()) {
            String line = tokenizer.nextToken().trim();
            // see if line contains IP address
            if (line.endsWith(localHost) && lastMacAddress != null) {
                return lastMacAddress;
            }
            // see if line contains MAC address
            int macAddressPosition = line.indexOf(":");
            if (macAddressPosition <= 0)
                continue;
            String macAddressCandidate = line.substring(macAddressPosition + 1).trim();
            if (windowsIsMacAddress(macAddressCandidate)) {
                lastMacAddress = macAddressCandidate;
                continue;
            }
        }
        ParseException ex = new ParseException("cannot read MAC address from [" + ipConfigResponse + "]", 0);
        ex.printStackTrace();
        throw ex;
    }
    private final static boolean windowsIsMacAddress(String macAddressCandidate) {
        // TODO: use a smart regular expression
        if (macAddressCandidate.length() != 17)
            return false;
        return true;
    }
    private final static String windowsRunIpConfigCommand() throws IOException {
        Process p = Runtime.getRuntime().exec("ipconfig /all");
        InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
        StringBuffer buffer= new StringBuffer();
        for (;;) {
            int c = stdoutStream.read();
            if (c == -1)
                break;
            buffer.append((char)c);
        }
        String outputText = buffer.toString();
        stdoutStream.close();
        return outputText;
    }
    /*
     * Main
     */
    public final static void main(String[] args) {
        try {
            System.out.println("Network infos");
            System.out.println("  Operating System: " + System.getProperty("os.name"));
            System.out.println("  IP/Localhost: " + InetAddress.getLocalHost().getHostAddress());
            System.out.println("  MAC Address: " + getMacAddress());
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
---------- end ----------

Best regards,
Jim Cakalic
0
 
LVL 2

Author Comment

by:egono
ID: 7046546
thanks to all!

Jim Cakalic - I would accept your comment as answer, but my linux server says "command not found" on the ifconfig command. I found the program on "/sbin/ifconfig", it seems my PATH envirnoment varaible doesn't contain /sbin/, so would like to know if the ifconfig program is always on /sbin/ ?
If yes then I would set the ifconfig command to "/sbin/ifconfig"

thanks again
0
 
LVL 35

Expert Comment

by:girionis
ID: 7046555
Change the path to point there by doing:

export PATH=$PATH:/sbin

  You can have you r path reloaded automaticalyl every time you turn on your computer by putting the PATH line in your .bashrc file.

  Hope it helps.
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 7047080
/sbin is the system binaries directory. I hadn't thought much about it before, but all info that I have been able to find indicates that ifconfig will be present there on linux systems. Of course, there are many variants of Unix that have been derived over the years. Another common (historical) path for ifconfig is /etc.

Should you be worried about accessibility, one document I found states: "The division between /bin and /sbin was not created for security reasons or to prevent users from seeing the operating system, but to provide a good partition between binaries that everyone uses and ones that are primarily used for administration tasks. There is no inherent security advantage in making /sbin off-limits for users."

Jim
0
 
LVL 2

Author Comment

by:egono
ID: 7095795
sorry for the delay ...

thanks again!
0
 
LVL 2

Author Comment

by:egono
ID: 7095812
btw - I'm using this implementation

 http://www.doomdark.org/doomdark/proj/jug/index.html

with jim's code to get the MAC address
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ForLoop Example 3 52
java stored proc example 9 44
Opening PDF on button click and fill new document 2 47
Running JavaFX on the Raspberry Pi 27 40
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This video teaches viewers about errors in exception handling.

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question