Java Host Address Get getHostAddress()

Here you can find the source of getHostAddress()

Description

Gets the host address, works around byte[] getAddress() looking negative

License

Open Source License

Return

address

Declaration

static short[] getHostAddress() 

Method Source Code


//package com.java2s;
/*//from   w w  w .  ja  v  a 2 s.  c o m
 * Copyright (C) 2000-2001  Ken McCrary
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Email: jkmccrary@yahoo.com
 */

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
    /**
     * Gets the host address, works around byte[] getAddress()
     * looking negative
     *
     * @return address
     */
    static short[] getHostAddress() {
        short[] address = new short[4];
        try {
            InetAddress netAddress = InetAddress.getLocalHost();
            String ipAddress = netAddress.getHostAddress();

            int beginIndex = 0;
            int endIndex = ipAddress.indexOf('.');

            address[0] = (short) Integer.parseInt(ipAddress.substring(beginIndex, endIndex));

            beginIndex = endIndex + 1;
            endIndex = ipAddress.indexOf('.', beginIndex);

            address[1] = (short) Integer.parseInt(ipAddress.substring(beginIndex, endIndex));

            beginIndex = endIndex + 1;
            endIndex = ipAddress.indexOf('.', beginIndex);

            address[2] = (short) Integer.parseInt(ipAddress.substring(beginIndex, endIndex));

            beginIndex = endIndex + 1;

            address[3] = (short) Integer.parseInt(ipAddress.substring(beginIndex, ipAddress.length()));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return address;
    }
}

Related

  1. getHost(final String address)
  2. getHostAddress()
  3. getHostAddress()
  4. getHostAddress()
  5. getHostAddress()
  6. getHostAddress()
  7. getHostAddress()
  8. getHostAddress()