Java uses the GetAddress method to obtain the IP address

Source: Internet
Author: User

The GetAddress method is similar to gethostaddress, whose only difference is that the Gethostaddress method returns an IP address in the form of a string, and 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 byte-type range of values is -128〜127. If a byte of the returned IP address is an integer greater than 127, a negative number is in the byte array. Because there is no unsigned byte type in Java, you must use an int or a long type to display a normal IP address. The following code demonstrates how to use GetAddress to return an IP address and how to convert an IP address to a positive integer.

Package mynet;
Import java.net.*;
public class MyIP
{
public static void Main (string[] args) throws Exception
{
InetAddress address = Inetaddress.getbyname ("www. Web site. 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 + "");
}
}
}
Run Result:
-45 100 26 122
211 100 26 122
From the above operation results can be seen, the first line output of the IP address is not converted, due to www. Web address. Net the first byte of IP addresses is greater than 127, thus outputting a negative number. The second line, because it converts each byte of an IP address to an int type, outputs a normal IP address.  

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.