2
import java.net.*;
import java.io.*;

public class ip_host {
    public static void main(String args[]) throws Exception {
        System.out.println("Enter the host name :");
        String n = new DataInputStream(System.in).readLine();

        InetAddress ipadd = InetAddress.getByName(n);

        System.out.println("IP address :" + ipadd);
    }
}

I have this program which finds the IP address, but i want to extend it to find the IP class as well.

Claus
  • 150
  • 8
MajoR
  • 121
  • 2
  • 11
  • Note that IP address classes are obsolete these days. The scarcity of IP4 addresses means that they are doled out in whatever size is actually required rather than the original large chunks. – Brian White Feb 24 '14 at 20:01

2 Answers2

2

You can do it manually by extracting the first triplet of the address and checking for appropriate ranges.

InetAddress address = InetAddress.getByName(host);
String firstTriplet = address.getHostAddress().
        substring(0,address.getHostAddress().indexOf('.'));

if (Integer.parseInt(firstTriplet) < 128) {
    System.out.println("Class A IP");
} else if (Integer.parseInt(firstTriplet) < 192) {
    System.out.println("Class B IP");
} else {
    System.out.println("Class C IP");
}

EDIT: Fixed classes

poroszd
  • 592
  • 4
  • 12
Warlord
  • 2,798
  • 16
  • 21
0

You can convert it to a byte[] and then check the highest byte:

byte[] address = ipadd.getAddress();
int highest = address[0] & 0xFF;

if (highest >= 0 && highest < 128) // class A
else if (highest < 192) // class B
else if (highest < 224) // class C
Jack
  • 131,802
  • 30
  • 241
  • 343