Samples‎ > ‎WinPack Samples‎ > ‎

Get Computer Name Example

import com.jniwrapper.*;
import com.jniwrapper.win32.FunctionName;
import com.jniwrapper.win32.LastErrorException;
import com.jniwrapper.win32.LastError;
import com.jniwrapper.win32.system.Kernel32;

/**
 * This example demonstrates how to retrive computer name, domain etc. using <code>GetComputerNameEx</code> API function.
 */
public class GetComputerNameExample {

    public static final int NetBIOS = 0;
    public static final int DnsHostname = 1;
    public static final int DnsDomain = 2;
    public static final int DnsFullyQualified = 3;
    public static final int PhysicalNetBIOS = 4;
    public static final int PhysicalDnsHostname = 5;
    public static final int PhysicalDnsDomain = 6;
    public static final int PhysicalDnsFullyQualified = 7;

    public static final int ERROR_MORE_DATA_IS_AVAILABLE = 234;

    private static final FunctionName FunctionGetComputerNameEx = new FunctionName("GetComputerNameEx");

    public static String getComputerName(int format) {
        final Function getComputerName = Kernel32.getInstance().getFunction(FunctionGetComputerNameEx.toString());

        Bool result = new Bool();

        LastError.clearLastErrorCode();

        // Get required buffer length first
        Int32 size = new Int32();
        long lastErrorCode = getComputerName.invoke(result,
                new Int(format),
                new Pointer.Void(),
                new Pointer(size));

        if (!result.getValue() && lastErrorCode!= ERROR_MORE_DATA_IS_AVAILABLE) {
            throw new LastErrorException(lastErrorCode);
        }

        Str name = new Str((int) size.getValue());
        lastErrorCode = getComputerName.invoke(result,
                new Int(format),
                new Pointer(name),
                new Pointer(size));

        if (!result.getValue()) {
            throw new LastErrorException(lastErrorCode);
        }

        return name.getValue();
    }

    public static void main(String[] args) {
        String value = getComputerName(DnsFullyQualified);
        System.out.println("Domain = " + value);
    }
}