Solved

Create a UUID without JNI

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

Expert Comment

by:girionis
Comment Utility
 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
Comment Utility
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
Comment Utility
 Oops.. Sorry, I thought you said with. Sorry again.
0
 
LVL 2

Author Comment

by:egono
Comment Utility
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
Comment Utility
 Why would you not want to use JNI?
0
 
LVL 2

Author Comment

by:egono
Comment Utility
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
Comment Utility
For what do you need a UUID?
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 5

Expert Comment

by:fontaine
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
/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
Comment Utility
sorry for the delay ...

thanks again!
0
 
LVL 2

Author Comment

by:egono
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
The viewer will learn how to implement Singleton Design Pattern in Java.

772 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now