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:org.hyperic.hq.bizapp.agent.client.SecureAgentConnection.java

@Override
protected Socket getSocket() throws IOException {
    SSLSocket socket;// www  .ja v a2  s  . com

    log.debug("Creating secure socket");

    try {
        // Check for configured agent read timeout from System properties
        int readTimeout;

        try {
            readTimeout = Integer.parseInt(System.getProperty(PROP_READ_TIMEOUT));
        } catch (NumberFormatException e) {
            readTimeout = READ_TIMEOUT;
        }

        // Check for configured agent post handshake timeout
        // from System properties
        int postHandshakeTimeout;
        try {
            postHandshakeTimeout = Integer.parseInt(System.getProperty(PROP_POST_HANDSHAKE_TIMEOUT));
        } catch (NumberFormatException e) {
            postHandshakeTimeout = POST_HANDSHAKE_TIMEOUT;
        }

        SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig, acceptUnverifiedCertificate);

        SSLSocketFactory factory = sslProvider.getSSLSocketFactory();

        // See the following links...
        // http://www.apache.org/dist/httpcomponents/httpcore/RELEASE_NOTES-4.1.x.txt
        // http://www-128.ibm.com/developerworks/forums/dw_thread.jsp?message=13695343&cat=10&thread=73546&treeDisplayType=threadmode1&forum=178#13695343
        // In any case, it would seem as though the bug has since been fixed in IBM's JRE, no need to work around it anymore...
        socket = (SSLSocket) factory.createSocket();

        // Make sure the InetAddress used to initialize the socket has a non-null hostname (empty string).
        // This prevents slow and unnecessary reverse DNS querying when the connection is opened.
        InetAddress withoutHost = InetAddress.getByName(this.agentAddress);
        InetAddress withHost = InetAddress.getByAddress("", withoutHost.getAddress());
        InetSocketAddress address = new InetSocketAddress(withHost, this.agentPort);

        socket.connect(address, readTimeout);

        // Set the socket timeout during the initial handshake to detect
        // connection issues with the agent.  
        socket.setSoTimeout(readTimeout);

        log.debug("Secure socket is connected to " + address + " - starting handshake.");

        socket.startHandshake();

        log.debug("SSL handshake complete");

        // [HHQ-3694] The timeout is set to a post handshake value.
        socket.setSoTimeout(postHandshakeTimeout);

    } catch (IOException exc) {
        IOException toThrow = new IOException(
                "Unable to connect to " + this.agentAddress + ":" + this.agentPort + ": " + exc.getMessage());
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    // Write our security settings
    try {
        DataOutputStream dOs;

        dOs = new DataOutputStream(socket.getOutputStream());
        dOs.writeUTF(this.authToken);
    } catch (IOException exc) {
        IOException toThrow = new IOException("Unable to write auth params to server");
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    return socket;
}

From source file:org.mule.transport.legstar.gen.AbstractTestTemplate.java

/**
 * Assuming the local machine is running Mule.
 * @return the local machine IP address//from w w  w  .j  a  va 2  s .  com
 */
public String getLocalIPAddress() {
    try {
        InetAddress addr = InetAddress.getLocalHost();
        byte[] ipAddr = addr.getAddress();
        String ipAddrStr = "";
        for (int i = 0; i < ipAddr.length; i++) {
            if (i > 0) {
                ipAddrStr += ".";
            }
            ipAddrStr += ipAddr[i] & 0xFF;
        }
        return ipAddrStr;
    } catch (UnknownHostException e) {
        return "";
    }

}

From source file:org.jasig.cas.adaptors.ldap.remote.RemoteAddressAuthenticationHandler.java

/**
 * Checks if a subnet contains a specific IP address.
 * /*from  w  ww  .ja v a  2  s.c o m*/
 * @param network The network address.
 * @param netmask The subnet mask.
 * @param ip The IP address to check.
 * @return A boolean value.
 */
private boolean containsAddress(final InetAddress network, final InetAddress netmask, final InetAddress ip) {
    if (log.isDebugEnabled()) {
        log.debug("Checking IP address: " + ip + " in " + network + " / " + netmask);
    }

    byte[] networkBytes = network.getAddress();
    byte[] netmaskBytes = netmask.getAddress();
    byte[] ipBytes = ip.getAddress();

    /* check IPv4/v6-compatibility or parameters: */
    if (networkBytes.length != netmaskBytes.length || netmaskBytes.length != ipBytes.length) {
        if (log.isDebugEnabled()) {
            log.debug("Network address " + network + ", subnet mask " + netmask + " and/or host address " + ip
                    + " have different sizes! (return false ...)");
        }
        return false;
    }

    /* Check if the masked network and ip addresses match: */
    for (int i = 0; i < netmaskBytes.length; i++) {
        int mask = netmaskBytes[i] & 0xff;
        if ((networkBytes[i] & mask) != (ipBytes[i] & mask)) {
            if (log.isDebugEnabled()) {
                log.debug(ip + " is not in " + network + " / " + netmask);
            }
            return false;
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(ip + " is in " + network + " / " + netmask);
    }
    return true;
}

From source file:org.opendaylight.controller.switchmanager.Subnet.java

private InetAddress getPrefixForAddress(InetAddress ip) {
    int bytes = this.subnetMaskLength / 8;
    int bits = this.subnetMaskLength % 8;
    byte modifiedByte;
    byte[] sn = ip.getAddress();
    if (bits > 0) {
        modifiedByte = (byte) (sn[bytes] >> (8 - bits));
        sn[bytes] = (byte) (modifiedByte << (8 - bits));
        bytes++;//w  w  w .j a v a 2s .  co  m
    }
    for (; bytes < sn.length; bytes++) {
        sn[bytes] = (byte) (0);
    }
    try {
        return InetAddress.getByAddress(sn);
    } catch (UnknownHostException e) {
        return null;
    }
}

From source file:com.qut.middleware.esoe.sso.servlet.SSOServlet.java

private void doRequest(HttpServletRequest request, HttpServletResponse response, RequestMethod method)
        throws ServletException, IOException {
    SSOProcessorData data;//from w ww  . jav a2s. c  o m

    data = (SSOProcessorData) request.getSession().getAttribute(SSOProcessorData.SESSION_NAME);

    String remoteAddress = request.getRemoteAddr();

    this.logger.debug("[SSO for {}] SSOServlet got {} request. SSO processor data element was {}",
            new Object[] { remoteAddress, method.toString(), data == null ? "null" : "not null" });

    if (data == null) {
        data = new SSOProcessorDataImpl();
        request.getSession().setAttribute(SSOProcessorData.SESSION_NAME, data);
    }

    data.setHttpRequest(request);
    data.setHttpResponse(response);
    data.setRequestMethod(method);

    String oldRemoteAddress = data.getRemoteAddress();
    if (oldRemoteAddress != null) {
        if (!oldRemoteAddress.equals(remoteAddress)) {
            this.logger.warn("[SSO for {}] IP address changed. Old address was: {}", remoteAddress,
                    oldRemoteAddress);
        }
    }

    data.setRemoteAddress(remoteAddress);

    try {
        SSOProcessor.result result = this.ssoProcessor.execute(data);
        this.logger.debug("[SSO for {}] SSOProcessor returned a result of {}",
                new Object[] { remoteAddress, String.valueOf(result) });
    } catch (SSOException e) {
        if (!data.isResponded()) {
            InetAddress inetAddress = Inet4Address.getByName(remoteAddress);
            String code = CalendarUtils.generateXMLCalendar().toString() + "-"
                    + new String(Hex.encodeHex(inetAddress.getAddress()));

            this.logger.error("[SSO for {}] {} Error occurred in SSOServlet.doPost. Exception was: {}", code,
                    e.getMessage());
            this.logger.debug(code + " Error occurred in SSOServlet.doPost. Exception follows", e);
            throw new ServletException(
                    "An error occurred during the sign-on process, and the session could not be established. Instance error is: "
                            + code);
        }
    }
}

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

public void deleteByInetAddress(InetAddress inetAddr) {
    getJdbcTemplate().update("delete from iaaddress where ipaddress = ?", inetAddr.getAddress());
}

From source file:org.getlantern.firetweet.util.net.FiretweetHostAddressResolver.java

private InetAddress[] fromAddressString(String host, String address) throws UnknownHostException {
    InetAddress inetAddress = InetAddress.getByName(address);
    if (inetAddress instanceof Inet4Address) {
        return new InetAddress[] { Inet4Address.getByAddress(host, inetAddress.getAddress()) };
    } else if (inetAddress instanceof Inet6Address) {
        return new InetAddress[] { Inet6Address.getByAddress(host, inetAddress.getAddress()) };
    }/*from w  w  w  . ja v a 2s  .  c  o  m*/
    throw new UnknownHostException("Bad address " + host + " = " + address);
}

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

public void deleteByInetAddress(InetAddress inetAddr) {
    getJdbcTemplate().update("delete from iaprefix where prefixaddress = ?", inetAddr.getAddress());
}

From source file:org.silverpeas.components.silvercrawler.util.IpAddressMatcher.java

public boolean matches(String address) {
    InetAddress remoteAddress = parseAddress(address);

    if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
        return false;
    }/*from  w  w w  .  j  a v  a 2 s .c  o  m*/

    if (nMaskBits < 0) {
        return remoteAddress.equals(requiredAddress);
    }

    byte[] remAddr = remoteAddress.getAddress();
    byte[] reqAddr = requiredAddress.getAddress();

    int oddBits = nMaskBits % 8;
    int nMaskBytes = nMaskBits / 8 + (oddBits == 0 ? 0 : 1);
    byte[] mask = new byte[nMaskBytes];

    Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte) 0xFF);

    if (oddBits != 0) {
        int finalByte = (1 << oddBits) - 1;
        finalByte <<= 8 - oddBits;
        mask[mask.length - 1] = (byte) finalByte;
    }

    for (int i = 0; i < mask.length; i++) {
        if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {
            return false;
        }
    }

    return true;
}

From source file:org.tamacat.httpd.util.IpAddressMatcher.java

public boolean matches(String address) {
    InetAddress remoteAddress = parseAddress(address);
    if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
        return false;
    }/*from  ww w .  j ava 2 s. c  o m*/

    if (nMaskBits < 0) {
        return remoteAddress.equals(requiredAddress);
    }

    byte[] remAddr = remoteAddress.getAddress();
    byte[] reqAddr = requiredAddress.getAddress();

    int oddBits = nMaskBits % 8;
    int nMaskBytes = nMaskBits / 8 + (oddBits == 0 ? 0 : 1);
    byte[] mask = new byte[nMaskBytes];

    Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte) 0xFF);

    if (oddBits != 0) {
        int finalByte = (1 << oddBits) - 1;
        finalByte <<= 8 - oddBits;
        mask[mask.length - 1] = (byte) finalByte;
    }

    for (int i = 0; i < mask.length; i++) {
        if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {
            return false;
        }
    }
    return true;
}