Java network programming from getting started to mastering (8): Obtaining an IP address using the GetAddress method

Source: Internet
Author: User

The GetAddress method is similar to gethostaddress, where the 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. The value range of byte type in Java 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 long type to display the normal IP address. The following code shows how to use GetAddress to return an IP address and how to convert an IP address into a positive integer.

Package mynet;
Import java.net.*;
Public class myip {    public static void main (String[] args)  throws exception     {         Inetaddress address = inetaddress.getbyname ("Www.csdn.net");         byte ip[] = address.getaddress ();         for  (BYTE&NBSP;IPSEGMENT&NBSP;:&NBSP;IP)              system.out.print (ipSegment +  " ");         system.out.println ("");         for  (BYTE&NBSP;IPSEGMENT&NBSP;:&NBSP;IP)          {             int newipsegment =  (ipsegment < 0) &NBSP;?&NBSP;256&NBSP;+&NBSP;IPSEGMENT&NBSP;:&NBsp;ipsegment;             system.out.print (newIPSegment +   " ");         }     }}

Operation Result:

-45 100 26 122 211 100 26 122

As can be seen from the running results above, the first line outputs an IP address that is not converted, because the first byte of the IP address of the www.csdn.net is greater than 127, so a negative number is output. The second line, by converting each byte of the IP address to the int type, outputs a normal IP address.

Java network programming from getting started to mastering (8): Obtaining an IP address using the GetAddress method

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.