Java Network Programming from entry to mastery (8): Get the IP address using the getAddress Method

Source: Internet
Author: User

GetAddressMethod andGetHostAddressSimilarly, the only difference between them isGetHostAddressThe method returns a string.IPAddress, andGetAddressThe method returnsByteArray formatIPAddress.GetAddressThe method is defined as follows:
Public Byte[] GetAddress ()This method returnsByteArrays are signed. InJavaMediumByteThe value range of the type is-128〜127. IfIPA byte of the address is greater127InByteThe array is a negative number. BecauseJavaIs not signedByteType.IPAddress, which must be usedIntOrLongType. The following codeDemonstrate how to useGetAddressReturnIPAddress, and howIPThe address is converted to an integer.
PackageMynet;

ImportJava.net.*;

Public ClassMyIP
{
Public Static VoidMain (String [] args)ThrowsException
{
InetAddress address=InetAddress. getByName ("Www.csdn.net");
ByteIp []=Address. getAddress ();
For(ByteIpSegment: ip)
System. out. print (ipSegment+ " ");
System. out. println ("");
For(ByteIpSegment: ip)
{
IntNewIPSegment=(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 unconvertedIPAddress, becauseWww.csdn.netOfIPThe first byte of the address is greater127Therefore, a negative number is output. The second lineIPEach byte of the address is converted

Related Article

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.