Example usage for java.net InetAddress getHostName

List of usage examples for java.net InetAddress getHostName

Introduction

In this page you can find the example usage for java.net InetAddress getHostName.

Prototype

public String getHostName() 

Source Link

Document

Gets the host name for this IP address.

Usage

From source file:org.opennms.netmgt.collectd.Collectd.java

/**
 * This method is responsible for handling interfaceDeleted events.
 * /* w w w . j ava 2 s . c  o  m*/
 * @param event
 *            The event to process.
 * @throws InsufficientInformationException
 */
private void handleInterfaceDeleted(Event event) throws InsufficientInformationException {
    EventUtils.checkNodeId(event);

    String ipAddr = event.getInterface();
    if (EventUtils.isNonIpInterface(ipAddr)) {
        LOG.debug("handleInterfaceDeleted: the deleted interface was a non-ip interface. Nothing to do here.");
        return;
    }

    Long nodeId = event.getNodeid();

    // Iterate over the collectable services list and mark any entries
    // which match the deleted nodeId/IP address pair for deletion
    synchronized (getCollectableServices()) {
        CollectableService cSvc = null;
        ListIterator<CollectableService> liter = getCollectableServices().listIterator();
        while (liter.hasNext()) {
            cSvc = liter.next();

            // Only interested in entries with matching nodeId and IP
            // address
            InetAddress addr = (InetAddress) cSvc.getAddress();
            if (!(cSvc.getNodeId() == nodeId && addr.getHostName().equals(ipAddr)))
                continue;

            synchronized (cSvc) {
                // Retrieve the CollectorUpdates object associated with
                // this CollectableService if one exists.
                CollectorUpdates updates = cSvc.getCollectorUpdates();

                // Now set the update's deletion flag so the next
                // time it is selected for execution by the scheduler
                // the collection will be skipped and the service will not
                // be rescheduled.
                LOG.debug(
                        "Marking CollectableService for deletion because an interface was deleted:  Service nodeid={}, deleted node:{}service address:{}deleted interface:{}",
                        cSvc.getNodeId(), nodeId, addr.getHostName(), ipAddr);

                updates.markForDeletion();
            }

            // Now safe to remove the collectable service from
            // the collectable services list
            liter.remove();
        }
    }

    LOG.debug("interfaceDeletedHandler: processing of interfaceDeleted event for {}/{} completed", nodeId,
            ipAddr);
}

From source file:edu.uci.ics.asterix.aoya.AsterixApplicationMaster.java

/**
 * Asks the RM for a particular host, nicely.
 * //from  w w  w.j  av  a  2s.  c o  m
 * @param host
 *            The host to request
 * @param cc
 *            Whether or not the host is the CC
 * @return A container request that is (hopefully) for the host we asked for.
 */
private ContainerRequest hostToRequest(String host, boolean cc) throws UnknownHostException {
    InetAddress hostIp = InetAddress.getByName(host);
    Priority pri = Records.newRecord(Priority.class);
    pri.setPriority(0);
    Resource capability = Records.newRecord(Resource.class);
    if (cc) {
        capability.setMemory(ccMem);
    } else {
        capability.setMemory(ncMem);
    }
    //we dont set anything else because we don't care about that and yarn doesn't honor it yet
    String[] hosts = new String[1];
    //TODO this is silly
    hosts[0] = hostIp.getHostName();
    LOG.info("IP addr: " + host + " resolved to " + hostIp.getHostName());
    ContainerRequest request = new ContainerRequest(capability, hosts, null, pri, false);
    LOG.info("Requested host ask: " + request.getNodes());
    return request;
}

From source file:org.opennms.ng.services.collectd.Collectd.java

/**
 * This method is responsible for handling serviceDeleted events.
 *
 * @param event The event to process.//  w w w.jav a2s.c  o m
 * @throws InsufficientInformationException
 */
private void handleServiceDeleted(Event event) throws InsufficientInformationException {
    EventUtils.checkNodeId(event);
    EventUtils.checkInterface(event);
    EventUtils.checkService(event);

    //INCORRECT; we now support all *sorts* of data collection.  This is *way* out of date
    // Currently only support SNMP data collection.
    //
    //if (!event.getService().equals("SNMP"))
    //    return;

    Long nodeId = event.getNodeid();
    String ipAddr = event.getInterface();
    String svcName = event.getService();

    // Iterate over the collectable services list and mark any entries
    // which match the nodeId/ipAddr of the deleted service
    // for deletion.
    synchronized (getCollectableServices()) {
        CollectableService cSvc = null;
        ListIterator<CollectableService> liter = getCollectableServices().listIterator();
        while (liter.hasNext()) {
            cSvc = liter.next();

            // Only interested in entries with matching nodeId, IP address
            // and service
            InetAddress addr = (InetAddress) cSvc.getAddress();

            //WATCH the brackets; there used to be an extra close bracket after the ipAddr comparison which borked this whole expression
            if (!(cSvc.getNodeId() == nodeId && addr.getHostName().equals(ipAddr)
                    && cSvc.getServiceName().equals(svcName))) {
                continue;
            }

            synchronized (cSvc) {
                // Retrieve the CollectorUpdates object associated with
                // this CollectableService if one exists.
                CollectorUpdates updates = cSvc.getCollectorUpdates();

                // Now set the update's deletion flag so the next
                // time it is selected for execution by the scheduler
                // the collection will be skipped and the service will not
                // be rescheduled.
                LOG.debug(
                        "Marking CollectableService for deletion because a service was deleted:  Service nodeid={}, deleted node:{}, "
                                + "service address:{}, deleted interface:{}, service servicename:{}, deleted service name:{}, event source {}",
                        cSvc.getNodeId(), nodeId, addr.getHostName(), ipAddr, cSvc.getServiceName(), svcName,
                        event.getSource());
                updates.markForDeletion();
            }

            // Now safe to remove the collectable service from
            // the collectable services list
            liter.remove();
        }
    }

    LOG.debug("serviceDeletedHandler: processing of serviceDeleted event for {}/{}/{} completed.", nodeId,
            ipAddr, svcName);
}

From source file:org.apache.hadoop.hbase.master.ServerManager.java

/**
 * Let the server manager know a new regionserver has come online
 * @param ia The remote address//from  w w w .  ja v a 2 s .  c o m
 * @param port The remote port
 * @param serverStartcode
 * @param serverCurrentTime The current time of the region server in ms
 * @return The ServerName we know this server as.
 * @throws IOException
 */
ServerName regionServerStartup(final InetAddress ia, final int port, final long serverStartcode,
        long serverCurrentTime) throws IOException {
    // Test for case where we get a region startup message from a regionserver
    // that has been quickly restarted but whose znode expiration handler has
    // not yet run, or from a server whose fail we are currently processing.
    // Test its host+port combo is present in serverAddresstoServerInfo.  If it
    // is, reject the server and trigger its expiration. The next time it comes
    // in, it should have been removed from serverAddressToServerInfo and queued
    // for processing by ProcessServerShutdown.
    ServerName sn = ServerName.valueOf(ia.getHostName(), port, serverStartcode);
    checkClockSkew(sn, serverCurrentTime);
    checkIsDead(sn, "STARTUP");
    if (!checkAndRecordNewServer(sn, ServerLoad.EMPTY_SERVERLOAD)) {
        LOG.warn("THIS SHOULD NOT HAPPEN, RegionServerStartup" + " could not record the server: " + sn);
    }
    return sn;
}

From source file:org.apache.coyote.http11.Http11Processor.java

/**
 * Parse host./*from  w w  w  . j  a  va2  s  .  com*/
 */
public void parseHost(MessageBytes valueMB) {

    if (valueMB == null || valueMB.isNull()) {
        // HTTP/1.0
        // Default is what the socket tells us. Overriden if a host is 
        // found/parsed
        request.setServerPort(socket.getLocalPort());
        InetAddress localAddress = socket.getLocalAddress();
        // Setting the socket-related fields. The adapter doesn't know 
        // about socket.
        request.setLocalHost(localAddress.getHostName());
        request.serverName().setString(localAddress.getHostName());
        return;
    }

    ByteChunk valueBC = valueMB.getByteChunk();
    byte[] valueB = valueBC.getBytes();
    int valueL = valueBC.getLength();
    int valueS = valueBC.getStart();
    int colonPos = -1;
    if (hostNameC.length < valueL) {
        hostNameC = new char[valueL];
    }

    boolean ipv6 = (valueB[valueS] == '[');
    boolean bracketClosed = false;
    for (int i = 0; i < valueL; i++) {
        char b = (char) valueB[i + valueS];
        hostNameC[i] = b;
        if (b == ']') {
            bracketClosed = true;
        } else if (b == ':') {
            if (!ipv6 || bracketClosed) {
                colonPos = i;
                break;
            }
        }
    }

    if (colonPos < 0) {
        if (sslSupport == null) {
            // 80 - Default HTTTP port
            request.setServerPort(80);
        } else {
            // 443 - Default HTTPS port
            request.setServerPort(443);
        }
        request.serverName().setChars(hostNameC, 0, valueL);
    } else {

        request.serverName().setChars(hostNameC, 0, colonPos);

        int port = 0;
        int mult = 1;
        for (int i = valueL - 1; i > colonPos; i--) {
            int charValue = HexUtils.DEC[(int) valueB[i + valueS]];
            if (charValue == -1) {
                // Invalid character
                error = true;
                // 400 - Bad request
                response.setStatus(400);
                break;
            }
            port = port + (charValue * mult);
            mult = 10 * mult;
        }
        request.setServerPort(port);

    }

}

From source file:org.apache.accumulo.core.client.mapreduce.InputFormatBase.java

/**
 * Read the metadata table to get tablets and match up ranges to them.
 *///from   w ww  . j  ava2  s  .  co  m
public List<InputSplit> getSplits(JobContext job) throws IOException {
    log.setLevel(getLogLevel(job.getConfiguration()));
    validateOptions(job.getConfiguration());

    String tableName = getTablename(job.getConfiguration());
    boolean autoAdjust = getAutoAdjustRanges(job.getConfiguration());
    List<Range> ranges = autoAdjust ? Range.mergeOverlapping(getRanges(job.getConfiguration()))
            : getRanges(job.getConfiguration());

    if (ranges.isEmpty()) {
        ranges = new ArrayList<Range>(1);
        ranges.add(new Range());
    }

    // get the metadata information for these ranges
    Map<String, Map<KeyExtent, List<Range>>> binnedRanges = new HashMap<String, Map<KeyExtent, List<Range>>>();
    TabletLocator tl;
    try {
        if (isOfflineScan(job.getConfiguration())) {
            binnedRanges = binOfflineTable(job, tableName, ranges);
            while (binnedRanges == null) {
                // Some tablets were still online, try again
                UtilWaitThread.sleep(100 + (int) (Math.random() * 100)); // sleep randomly between 100 and 200 ms
                binnedRanges = binOfflineTable(job, tableName, ranges);
            }
        } else {
            Instance instance = getInstance(job.getConfiguration());
            String tableId = null;
            tl = getTabletLocator(job.getConfiguration());
            // its possible that the cache could contain complete, but old information about a tables tablets... so clear it
            tl.invalidateCache();
            while (!tl.binRanges(ranges, binnedRanges).isEmpty()) {
                if (!(instance instanceof MockInstance)) {
                    if (tableId == null)
                        tableId = Tables.getTableId(instance, tableName);
                    if (!Tables.exists(instance, tableId))
                        throw new TableDeletedException(tableId);
                    if (Tables.getTableState(instance, tableId) == TableState.OFFLINE)
                        throw new TableOfflineException(instance, tableId);
                }
                binnedRanges.clear();
                log.warn("Unable to locate bins for specified ranges. Retrying.");
                UtilWaitThread.sleep(100 + (int) (Math.random() * 100)); // sleep randomly between 100 and 200 ms
                tl.invalidateCache();
            }
        }
    } catch (Exception e) {
        throw new IOException(e);
    }

    ArrayList<InputSplit> splits = new ArrayList<InputSplit>(ranges.size());
    HashMap<Range, ArrayList<String>> splitsToAdd = null;

    if (!autoAdjust)
        splitsToAdd = new HashMap<Range, ArrayList<String>>();

    HashMap<String, String> hostNameCache = new HashMap<String, String>();

    for (Entry<String, Map<KeyExtent, List<Range>>> tserverBin : binnedRanges.entrySet()) {
        String ip = tserverBin.getKey().split(":", 2)[0];
        String location = hostNameCache.get(ip);
        if (location == null) {
            InetAddress inetAddress = InetAddress.getByName(ip);
            location = inetAddress.getHostName();
            hostNameCache.put(ip, location);
        }

        for (Entry<KeyExtent, List<Range>> extentRanges : tserverBin.getValue().entrySet()) {
            Range ke = extentRanges.getKey().toDataRange();
            for (Range r : extentRanges.getValue()) {
                if (autoAdjust) {
                    // divide ranges into smaller ranges, based on the
                    // tablets
                    splits.add(new RangeInputSplit(tableName, ke.clip(r), new String[] { location }));
                } else {
                    // don't divide ranges
                    ArrayList<String> locations = splitsToAdd.get(r);
                    if (locations == null)
                        locations = new ArrayList<String>(1);
                    locations.add(location);
                    splitsToAdd.put(r, locations);
                }
            }
        }
    }

    if (!autoAdjust)
        for (Entry<Range, ArrayList<String>> entry : splitsToAdd.entrySet())
            splits.add(new RangeInputSplit(tableName, entry.getKey(), entry.getValue().toArray(new String[0])));
    return splits;
}

From source file:org.opennms.netmgt.collectd.Collectd.java

/**
 * This method is responsible for handling serviceDeleted events.
 * // ww  w. j a  va2s .c o m
 * @param event
 *            The event to process.
 * @throws InsufficientInformationException 
 * 
 */
private void handleServiceDeleted(Event event) throws InsufficientInformationException {
    EventUtils.checkNodeId(event);
    EventUtils.checkInterface(event);
    EventUtils.checkService(event);

    //INCORRECT; we now support all *sorts* of data collection.  This is *way* out of date
    // Currently only support SNMP data collection.
    //
    //if (!event.getService().equals("SNMP"))
    //    return;

    Long nodeId = event.getNodeid();
    String ipAddr = event.getInterface();
    String svcName = event.getService();

    // Iterate over the collectable services list and mark any entries
    // which match the nodeId/ipAddr of the deleted service
    // for deletion.
    synchronized (getCollectableServices()) {
        CollectableService cSvc = null;
        ListIterator<CollectableService> liter = getCollectableServices().listIterator();
        while (liter.hasNext()) {
            cSvc = liter.next();

            // Only interested in entries with matching nodeId, IP address
            // and service
            InetAddress addr = (InetAddress) cSvc.getAddress();

            //WATCH the brackets; there used to be an extra close bracket after the ipAddr comparison which borked this whole expression
            if (!(cSvc.getNodeId() == nodeId && addr.getHostName().equals(ipAddr)
                    && cSvc.getServiceName().equals(svcName)))
                continue;

            synchronized (cSvc) {
                // Retrieve the CollectorUpdates object associated with
                // this CollectableService if one exists.
                CollectorUpdates updates = cSvc.getCollectorUpdates();

                // Now set the update's deletion flag so the next
                // time it is selected for execution by the scheduler
                // the collection will be skipped and the service will not
                // be rescheduled.
                LOG.debug(
                        "Marking CollectableService for deletion because a service was deleted:  Service nodeid={}, deleted node:{}, service address:{}, deleted interface:{}, service servicename:{}, deleted service name:{}, event source {}",
                        cSvc.getNodeId(), nodeId, addr.getHostName(), ipAddr, cSvc.getServiceName(), svcName,
                        event.getSource());
                updates.markForDeletion();
            }

            // Now safe to remove the collectable service from
            // the collectable services list
            liter.remove();
        }
    }

    LOG.debug("serviceDeletedHandler: processing of serviceDeleted event for {}/{}/{} completed.", nodeId,
            ipAddr, svcName);
}

From source file:weka.server.WekaServer.java

@Override
public void run(Object toRun, String[] args) throws IllegalArgumentException {
    if (!(toRun instanceof WekaServer)) {
        throw new IllegalArgumentException("Supplied object is not a WekaServer!!");
    }//from   w  ww.  j  av a 2  s.  c o m
    WekaServer server = (WekaServer) toRun;

    try {
        if (args.length > 0 && (args[0].equalsIgnoreCase("-h") || args[0].equalsIgnoreCase("-help"))) {
            System.out.println(WekaServer.commandLineUsage());
            System.exit(0);
        }

        String hostname = null;
        String port = null;
        boolean daemon = false;
        int numSlots = -1;
        double loadAdjust = 0.0;
        String master = null;
        long purgeInterval = 0;

        // process options
        for (int i = 0; i < args.length; i++) {
            if (args[i].equalsIgnoreCase("-host")) {
                if (++i == args.length) {
                    System.out.println(WekaServer.commandLineUsage());
                    System.exit(1);
                }
                hostname = args[i];
            } else if (args[i].equalsIgnoreCase("-port")) {
                if (++i == args.length) {
                    System.out.println(WekaServer.commandLineUsage());
                    System.exit(1);
                }
                port = args[i];
            } else if (args[i].equalsIgnoreCase("-slots")) {
                if (++i == args.length) {
                    System.out.println(WekaServer.commandLineUsage());
                    System.exit(1);
                }
                numSlots = Integer.parseInt(args[i]);
            } else if (args[i].equalsIgnoreCase("-load-adjust")) {
                if (++i == args.length) {
                    System.out.println(WekaServer.commandLineUsage());
                    System.exit(1);
                }
                loadAdjust = Double.parseDouble(args[i]);
            } else if (args[i].equalsIgnoreCase("-master")) {
                if (++i == args.length) {
                    System.out.println(WekaServer.commandLineUsage());
                    System.exit(1);
                }
                master = args[i];
            } else if (args[i].equalsIgnoreCase("-staleTime")) {
                if (++i == args.length) {
                    System.out.println(WekaServer.commandLineUsage());
                    System.exit(1);
                }
                purgeInterval = Long.parseLong(args[i]);
            } else if (args[i].equalsIgnoreCase("-daemon")) {
                daemon = true;
            } else {
                System.out.println(WekaServer.commandLineUsage());
                System.exit(1);
            }
        }

        InetAddress localhost = null;
        if (hostname == null) {
            // try to get the hostname
            try {
                localhost = InetAddress.getLocalHost();
                if (localhost != null) {
                    System.out.println("Host name: " + localhost.getHostName());
                    hostname = localhost.getHostName();
                } else {
                    hostname = "localhost";
                }
            } catch (Exception ex) {
            }
        }

        if (port == null) {
            port = "" + WekaServer.PORT;
        }

        server.setHostname(hostname);
        server.setPort(Integer.parseInt(port));
        if (numSlots > 0) {
            server.setNumExecutionSlots(numSlots);
        }
        if (loadAdjust > 0) {
            server.setLoadAdjust(loadAdjust);
        }
        if (purgeInterval != 0) {
            server.setStaleTaskTime(purgeInterval);
        }
        server.setDaemon(daemon);
        server.setMaster(master);

        server.startJettyServer();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager.java

/**
 * Register the given datanode with the namenode. NB: the given
 * registration is mutated and given back to the datanode.
 *
 * @param nodeReg//from  w  w  w .j a  v  a  2  s.co  m
 *     the datanode registration
 * @throws DisallowedDatanodeException
 *     if the registration request is
 *     denied because the datanode does not match includes/excludes
 */
public void registerDatanode(DatanodeRegistration nodeReg) throws DisallowedDatanodeException, IOException {
    InetAddress dnAddress = Server.getRemoteIp();
    if (dnAddress != null) {
        // Mostly called inside an RPC, update ip and peer hostname
        String hostname = dnAddress.getHostName();
        String ip = dnAddress.getHostAddress();
        if (checkIpHostnameInRegistration && !isNameResolved(dnAddress)) {
            // Reject registration of unresolved datanode to prevent performance
            // impact of repetitive DNS lookups later.
            final String message = "hostname cannot be resolved (ip=" + ip + ", hostname=" + hostname + ")";
            LOG.warn("Unresolved datanode registration: " + message);
            throw new DisallowedDatanodeException(nodeReg, message);
        }
        // update node registration with the ip and hostname from rpc request
        nodeReg.setIpAddr(ip);
        nodeReg.setPeerHostName(hostname);
    }

    nodeReg.setExportedKeys(blockManager.getBlockKeys());

    // Checks if the node is not on the hosts list.  If it is not, then
    // it will be disallowed from registering.
    if (!hostFileManager.isIncluded(nodeReg)) {
        throw new DisallowedDatanodeException(nodeReg);
    }

    NameNode.stateChangeLog
            .info("BLOCK* registerDatanode: from " + nodeReg + " storage " + nodeReg.getDatanodeUuid());

    DatanodeDescriptor nodeS = datanodeMap.get(nodeReg.getDatanodeUuid());
    DatanodeDescriptor nodeN = host2DatanodeMap.getDatanodeByXferAddr(nodeReg.getIpAddr(),
            nodeReg.getXferPort());

    if (nodeN != null && nodeN != nodeS) {
        NameNode.LOG.info("BLOCK* registerDatanode: " + nodeN);
        // nodeN previously served a different data storage,
        // which is not served by anybody anymore.
        removeDatanode(nodeN, false);
        // physically remove node from datanodeMap
        wipeDatanode(nodeN);
        nodeN = null;
    }

    if (nodeS != null) {
        if (nodeN == nodeS) {
            // The same datanode has been just restarted to serve the same data
            // storage. We do not need to remove old data blocks, the delta will
            // be calculated on the next block report from the datanode
            if (NameNode.stateChangeLog.isDebugEnabled()) {
                NameNode.stateChangeLog.debug("BLOCK* registerDatanode: " + "node restarted.");
            }
        } else {
            // nodeS is found
            /* The registering datanode is a replacement node for the existing
              data storage, which from now on will be served by a new node.
              If this message repeats, both nodes might have same storageID
              by (insanely rare) random chance. User needs to restart one of the
              nodes with its data cleared (or user can just remove the StorageID
              value in "VERSION" file under the data directory of the datanode,
              but this is might not work if VERSION file format has changed
            */
            NameNode.stateChangeLog.info("BLOCK* registerDatanode: " + nodeS + " is replaced by " + nodeReg
                    + " with the same storageID " + nodeReg.getDatanodeUuid());
        }
        // update cluster map
        getNetworkTopology().remove(nodeS);
        if (shouldCountVersion(nodeS)) {
            decrementVersionCount(nodeS.getSoftwareVersion());
        }
        nodeS.updateRegInfo(nodeReg);

        nodeS.setSoftwareVersion(nodeReg.getSoftwareVersion());
        nodeS.setDisallowed(false); // Node is in the include list

        // resolve network location
        if (this.rejectUnresolvedTopologyDN) {
            nodeS.setNetworkLocation(resolveNetworkLocation(nodeS));
            nodeS.setDependentHostNames(getNetworkDependencies(nodeS));
        } else {
            nodeS.setNetworkLocation(resolveNetworkLocationWithFallBackToDefaultLocation(nodeS));
            nodeS.setDependentHostNames(getNetworkDependenciesWithDefault(nodeS));
        }
        getNetworkTopology().add(nodeS);

        // also treat the registration message as a heartbeat
        heartbeatManager.register(nodeS);
        incrementVersionCount(nodeS.getSoftwareVersion());
        startDecommissioningIfExcluded(nodeS);
        return;
    }

    // register new datanode
    DatanodeDescriptor nodeDescr = new DatanodeDescriptor(this.storageMap, nodeReg,
            NetworkTopology.DEFAULT_RACK);

    // resolve network location
    if (this.rejectUnresolvedTopologyDN) {
        nodeDescr.setNetworkLocation(resolveNetworkLocation(nodeDescr));
        nodeDescr.setDependentHostNames(getNetworkDependencies(nodeDescr));
    } else {
        nodeDescr.setNetworkLocation(resolveNetworkLocationWithFallBackToDefaultLocation(nodeDescr));
        nodeDescr.setDependentHostNames(getNetworkDependenciesWithDefault(nodeDescr));
    }
    nodeDescr.setSoftwareVersion(nodeReg.getSoftwareVersion());
    addDatanode(nodeDescr);

    // also treat the registration message as a heartbeat
    // no need to update its timestamp
    // because its is done when the descriptor is created
    heartbeatManager.addDatanode(nodeDescr);
    incrementVersionCount(nodeReg.getSoftwareVersion());
    startDecommissioningIfExcluded(nodeDescr);
}

From source file:org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static String resolveIP(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    String sRC = "";
    if (ArgList.length == 2) {
        try {// w w w. ja v a2  s. c o  m
            InetAddress addr = InetAddress.getByName(Context.toString(ArgList[0]));
            if (Context.toString(ArgList[1]).equals("IP")) {
                sRC = addr.getHostName();
            } else {
                sRC = addr.getHostAddress();
            }
            if (sRC.equals(Context.toString(ArgList[0]))) {
                sRC = "-";
            }
        } catch (Exception e) {
            sRC = "-";
        }
    } else {
        throw Context.reportRuntimeError("The function call resolveIP requires 2 arguments.");
    }

    return sRC;
}