Java uses 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 java.net .*;
Public class MyIP
{
Public static void main (String [] args) throws Exception
{
InetAddress address = InetAddress. getByName ("www. url. net ");
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 www. Website. net 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: info-contact@alibabacloud.com 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.