Example usage for java.net InetAddress getAddress

List of usage examples for java.net InetAddress getAddress

Introduction

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

Prototype

public byte[] getAddress() 

Source Link

Document

Returns the raw IP address of this InetAddress object.

Usage

From source file:com.jagornet.dhcp.db.JdbcIaPrefixDAO.java

public IaPrefix getByInetAddress(InetAddress inetAddr) {
    return getJdbcTemplate().queryForObject("select * from iaprefix where ipprefix = ?",
            new IaPrefixRowMapper(), inetAddr.getAddress());
}

From source file:org.apache.flink.runtime.taskmanager.TaskManager.java

/**
 * Determines the IP address of the interface from which the TaskManager can connect to the given JobManager
 * IP address./*from  ww w. j  a  va2  s .  co m*/
 * 
 * @param jobManagerAddress The socket address to connect to.
 * @return The IP address of the interface that connects to the JobManager.
 * @throws IOException If no connection could be established.
 */
private static InetAddress getTaskManagerAddress(InetSocketAddress jobManagerAddress) throws IOException {
    AddressDetectionState strategy = AddressDetectionState.ADDRESS;

    while (true) {
        Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface n = e.nextElement();
            Enumeration<InetAddress> ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = ee.nextElement();
                switch (strategy) {
                case ADDRESS:
                    if (hasCommonPrefix(jobManagerAddress.getAddress().getAddress(), i.getAddress())) {
                        if (tryToConnect(i, jobManagerAddress, strategy.getTimeout())) {
                            LOG.info("Determined " + i + " as the TaskTracker's own IP address");
                            return i;
                        }
                    }
                    break;
                case FAST_CONNECT:
                case SLOW_CONNECT:
                    boolean correct = tryToConnect(i, jobManagerAddress, strategy.getTimeout());
                    if (correct) {
                        LOG.info("Determined " + i + " as the TaskTracker's own IP address");
                        return i;
                    }
                    break;
                default:
                    throw new RuntimeException("Unkown address detection strategy: " + strategy);
                }
            }
        }
        // state control
        switch (strategy) {
        case ADDRESS:
            strategy = AddressDetectionState.FAST_CONNECT;
            break;
        case FAST_CONNECT:
            strategy = AddressDetectionState.SLOW_CONNECT;
            break;
        case SLOW_CONNECT:
            throw new RuntimeException("The TaskManager is unable to connect to the JobManager (Address: '"
                    + jobManagerAddress + "').");
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Defaulting to detection strategy {}", strategy);
        }
    }
}

From source file:org.slc.sli.ingestion.processors.ControlFilePreProcessor.java

private void auditSecurityEvent(NewBatchJob currentJob, ControlFile controlFile) {
    byte[] ipAddr = null;
    try {/* www. ja  v  a2  s.c  om*/
        InetAddress addr = InetAddress.getLocalHost();

        // Get IP Address
        ipAddr = addr.getAddress();

    } catch (UnknownHostException e) {
        LogUtil.error(LOG, "Error getting local host", e);
    }

    String edOrg = tenantDA.getTenantEdOrg(currentJob.getTopLevelSourceId());
    if (edOrg == null) {
        edOrg = "";
    }

    List<String> userRoles = Collections.emptyList();
    SecurityEvent event = new SecurityEvent();
    event.setTenantId(controlFile.getConfigProperties().getProperty("tenantId"));
    event.setUser("");
    event.setUserEdOrg(edOrg);
    event.setTargetEdOrgList(edOrg); //@TA10431 - change targetEdOrg from scalar to list
    event.setActionUri("processUsingNewBatchJob");
    event.setAppId("Ingestion");
    event.setOrigin("");
    event.setExecutedOn(ipAddr[0] + "." + ipAddr[1] + "." + ipAddr[2] + "." + ipAddr[3]);
    event.setCredential("");
    event.setUserOrigin("");
    event.setTimeStamp(new Date());
    event.setProcessNameOrId(ManagementFactory.getRuntimeMXBean().getName());
    event.setClassName(this.getClass().getName());
    event.setLogLevel(LogLevelType.TYPE_INFO);
    event.setRoles(userRoles);
    event.setLogMessage("Ingestion process started.");

    audit(event);
}

From source file:org.mariotaku.twidere.util.net.TwidereDns.java

private InetAddress[] fromResolver(String originalHost, String host, int depth) throws IOException {
    final Resolver dns = getResolver();
    final Lookup lookup = new Lookup(new Name(host), Type.A, DClass.IN);
    final Record[] records;
    lookup.setResolver(dns);/*from ww w. j  av  a  2  s  .c o m*/
    lookup.run();
    final int result = lookup.getResult();
    if (result != Lookup.SUCCESSFUL) {
        throw new UnknownHostException("Unable to resolve " + host + ", " + lookup.getErrorString());
    }
    records = lookup.getAnswers();
    final ArrayList<InetAddress> resolvedAddresses = new ArrayList<>();
    // Test each IP address resolved.
    long ttl = -1;
    for (final Record record : records) {
        if (ttl == -1) {
            ttl = record.getTTL();
        }
        if (record instanceof ARecord) {
            final InetAddress ipv4Addr = ((ARecord) record).getAddress();
            resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv4Addr.getAddress()));
        } else if (record instanceof AAAARecord) {
            final InetAddress ipv6Addr = ((AAAARecord) record).getAddress();
            resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv6Addr.getAddress()));
        }
    }
    if (!resolvedAddresses.isEmpty()) {
        final InetAddress[] hostAddr = resolvedAddresses.toArray(new InetAddress[resolvedAddresses.size()]);
        putCache(originalHost, hostAddr, ttl, TimeUnit.SECONDS);
        if (BuildConfig.DEBUG) {
            Log.v(RESOLVER_LOGTAG, "Resolved " + Arrays.toString(hostAddr));
        }
        return hostAddr;
    }
    // No address is reachable, but I believe the IP is correct.

    for (final Record record : records) {
        if (record instanceof CNAMERecord)
            return resolveInternal(originalHost, ((CNAMERecord) record).getTarget().toString(), depth + 1);
    }
    return null;
}

From source file:org.apache.cassandra.db.clock.IncrementCounterContext.java

public byte[] cleanNodeCounts(byte[] context, InetAddress node) {
    // calculate node id
    byte[] nodeId = node.getAddress();

    // look for this node id
    for (int offset = HEADER_LENGTH; offset < context.length; offset += stepLength) {
        if (FBUtilities.compareByteSubArrays(context, offset, nodeId, 0, idLength) != 0)
            continue;

        // node id found: remove node count
        byte[] truncatedContext = new byte[context.length - stepLength];
        System.arraycopy(context, 0, truncatedContext, 0, offset);
        System.arraycopy(context, offset + stepLength, truncatedContext, offset,
                context.length - (offset + stepLength));
        return truncatedContext;
    }//from   ww  w.  ja v a2s. c om

    return context;
}

From source file:com.xsdn.main.util.Ip4Network.java

/**
 * {@inheritDoc}/*from   w  w  w  .  j  a  v  a  2 s  .c  o m*/
 */
@Override
InetAddress init(InetAddress iaddr, int prefix) {
    int addr = NumberUtils.toInteger(iaddr.getAddress());
    int mask = getNetMask(prefix);
    int maskedAddr = addr & mask;
    address = maskedAddr;
    netMask = mask;
    return getInetAddress(maskedAddr);
}

From source file:hudson.plugins.dimensionsscm.ArtifactUploader.java

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws IOException, InterruptedException {
    long key = -1;
    Logger.Debug("Invoking perform callout " + this.getClass().getName());
    FilePath workspace = build.getWorkspace();
    boolean bRet = false;
    boolean isStream = false;

    try {/*from www. j  a  v a  2 s.co m*/
        if (!(build.getProject().getScm() instanceof DimensionsSCM)) {
            listener.fatalError("[DIMENSIONS] This plugin only works with the Dimensions SCM engine.");
            build.setResult(Result.FAILURE);
            throw new IOException("[DIMENSIONS] This plugin only works with a Dimensions SCM engine");
        }

        if (build.getResult() == Result.SUCCESS) {
            DimensionsSCM scm = (DimensionsSCM) build.getProject().getScm();
            DimensionsAPI dmSCM = new DimensionsAPI();

            Logger.Debug("Calculating version of Dimensions...");

            int version = 2009;
            key = dmSCM.login(scm.getJobUserName(), scm.getJobPasswd(), scm.getJobDatabase(),
                    scm.getJobServer());

            if (key > 0) {
                // Get the server version
                Logger.Debug("Login worked.");
                version = dmSCM.getDmVersion();
                if (version == 0) {
                    version = 2009;
                }
                if (version != 10) {
                    isStream = dmSCM.isStream(key, scm.getProject());
                }
                dmSCM.logout(key);
            }

            // Get the details of the master
            InetAddress netAddr = InetAddress.getLocalHost();
            byte[] ipAddr = netAddr.getAddress();
            String hostname = netAddr.getHostName();

            String projectName = build.getProject().getName();
            int buildNo = build.getNumber();

            Logger.Debug("Checking if master or slave...");

            boolean master = false;
            GetHostDetailsTask buildHost = new GetHostDetailsTask(hostname);
            master = workspace.act(buildHost);

            if (master) {
                // Running on master...
                listener.getLogger().println("[DIMENSIONS] Running checkin on master...");
                listener.getLogger().flush();

                // Using Java API because this allows the plugin to work on platforms
                // where Dimensions has not been ported, e.g. MAC OS, which is what
                // I use
                CheckInAPITask task = new CheckInAPITask(build, scm, buildNo, projectName, version, this,
                        workspace, listener);
                bRet = workspace.act(task);
            } else {
                // Running on slave... Have to use the command line as Java API will not
                // work on remote hosts. Cannot serialise it...

                {
                    // VariableResolver does not appear to be serialisable either, so...
                    VariableResolver<String> myResolver = build.getBuildVariableResolver();

                    String requests = myResolver.resolve("DM_TARGET_REQUEST");

                    listener.getLogger().println("[DIMENSIONS] Running checkin on slave...");
                    listener.getLogger().flush();

                    CheckInCmdTask task = new CheckInCmdTask(scm.getJobUserName(), scm.getJobPasswd(),
                            scm.getJobDatabase(), scm.getJobServer(), scm.getProject(), requests,
                            isForceCheckIn(), isForceTip(), getPatterns(), version, isStream, buildNo,
                            projectName, getOwningPart(), workspace, listener);
                    bRet = workspace.act(task);
                }
            }
        } else {
            bRet = true;
        }
        if (!bRet) {
            build.setResult(Result.FAILURE);
        }
    } catch (Exception e) {
        listener.fatalError("Unable to load build artifacts into Dimensions - " + e.getMessage());
        build.setResult(Result.FAILURE);
        return false;
    } finally {
    }
    return bRet;
}

From source file:org.lwes.EventTest.java

@Test
public void testGetInetAddressAsBytes() throws EventSystemException, UnknownHostException {
    Event evt = createEvent();//  w  w  w  . j  a v  a  2 s.co  m
    evt.setEventName("Test");
    final InetAddress localhost = InetAddress.getLocalHost();
    evt.setByteArray("ip", localhost.getAddress());
    byte[] iparr = evt.getByteArray("ip");
    InetAddress a = InetAddress.getByAddress(iparr);
    assertNotNull(a);
    assertEquals(localhost, a);
}

From source file:com.offbynull.portmapper.pcp.PcpRequest.java

/**
 * Dump this PCP request in to a byte buffer.
 * @param dst byte buffer to dump to//w w  w  . j  a va  2s  . co m
 * @param selfAddress IP address of this machine on the interface used to access the PCP server
 * @throws NullPointerException if any argument is {@code null}
 * @throws BufferOverflowException if {@code dst} doesn't have enough space to write this option
 * @throws ReadOnlyBufferException if {@code dst} is read-only
 */
public final void dump(ByteBuffer dst, InetAddress selfAddress) {
    Validate.notNull(dst);
    Validate.notNull(selfAddress);

    dst.put((byte) 2);
    dst.put((byte) op); // topmost bit should be 0, because op is between 0 to 127, which means r-flag = 0
    dst.putShort((short) 0);
    dst.putInt((int) lifetime);

    byte[] selfAddressArr = selfAddress.getAddress();
    switch (selfAddressArr.length) {
    case 4: {
        // convert ipv4 address to ipv4-mapped ipv6 address
        for (int i = 0; i < 10; i++) {
            dst.put((byte) 0);
        }

        for (int i = 0; i < 2; i++) {
            dst.put((byte) 0xff);
        }

        dst.put(selfAddressArr);
        break;
    }
    case 16: {
        dst.put(selfAddressArr);
        break;
    }
    default:
        throw new IllegalArgumentException(); // should never happen
    }

    dumpOpCodeSpecificInformation(dst);

    for (PcpOption option : options) {
        option.dump(dst);
    }
}

From source file:org.opendaylight.netvirt.dhcpservice.api.DHCP.java

public DHCP setCiaddr(InetAddress dhcpCiaddr) {
    byte[] ciaddr = dhcpCiaddr.getAddress();
    fieldValues.put(CIADDR, ciaddr);//w w  w. j a va  2 s . com
    return this;
}