Java 如何检查ip地址范围是否属于a类、B类和C类

Java 如何检查ip地址范围是否属于a类、B类和C类,java,class,ip,addressing,Java,Class,Ip,Addressing,我有一个查找IP地址的程序,但我想扩展它以查找IP类。您可以将其转换为字节[],然后检查最高字节: 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 D

我有一个查找IP地址的程序,但我想扩展它以查找IP类。

您可以将其转换为字节[],然后检查最高字节:

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);
    }
}
byte[]address=ipadd.getAddress();
int highest=地址[0]&0xFF;
如果(最高值>=0&&highest<128)//A类
else if(最高<192)//B类
else if(最高<224)//C类

您可以通过提取地址的第一个三元组并检查适当的范围来手动执行此操作

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
InetAddress=InetAddress.getByName(主机);
字符串firstTriplet=address.getHostAddress()。
子字符串(0,address.getHostAddress().indexOf('.');
if(Integer.parseInt(firstTriplet)<128){
系统输出打印项次(“A类IP”);
}else if(Integer.parseInt(firstTriplet)<192){
系统输出打印项次(“B类IP”);
}否则{
系统输出打印项次(“C类IP”);
}
编辑
固定类

请注意,IP地址类现在已经过时了。IP4地址的稀缺性意味着它们被分配到实际需要的任何大小,而不是原来的大块。
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");
}