Use the getaddress method to obtain the IP address

Source: Internet
Author: User

The getaddress method is similar to the gethostaddress method. The only difference between the gethostaddress method and gethostaddress method is that the gethostaddress method returns an IP address in the form of a string, while the getaddress method returns an IP address in the form of a byte array. The getaddress method is defined as follows:

public byte[] getAddress()

The byte array returned by this method is signed. In Java, the value range of the byte type is-128 ~ 127. If a byte of the returned IP address is an integer greater than 127, It is a negative number in the byte array. Because Java does not have an unsigned byte type, Int or long type must be used to display normal IP addresses. The following code demonstrates how to use getaddress to return IP addresses and convert IP addresses into integers.

package mynet;import*;public class MyIP{    public static void main(String[] args) throws Exception    {        InetAddress address = InetAddress.getByName("");        byte ip[] = address.getAddress();        for (byte ipSegment : ip)            System.out.print(ipSegment + " ");        System.out.println("");        for (byte ipSegment : ip)        {            int newIPSegment = (ipSegment < 0) ? 256 + ipSegment : ipSegment;            System.out.print(newIPSegment + " ");        }    }}

Running result:

-45 100 26 122 211 100 26 122

From the preceding running results, we can see that the first line outputs unconverted IP addresses. Because the first byte of the IP address of is greater than 127, a negative number is output. The second line outputs a normal IP address because each byte of the IP address is converted to the int type.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.