【问题标题】:How do i check a ip address range whether it falls in Class A,Class B,Class C如何检查 IP 地址范围是否属于 A 类、B 类、C 类
【发布时间】:2014-02-22 17:08:00
【问题描述】:
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);
    }
}

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

【问题讨论】:

  • 请注意,IP 地址类别如今已过时。 IP4 地址的稀缺性意味着它们被分配到实际需要的任何大小,而不是原来的大块。

标签: java class ip addressing


【解决方案1】:

您可以通过提取地址的第一个三元组并检查适当的范围来手动完成。

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");
}

编辑: 固定类

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2018-01-09
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 2012-03-26
      相关资源
      最近更新 更多