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

我有这个程序可以找到 IP 地址,但我想扩展它以找到 IP 类。

4

2 回答 2

2

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

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

编辑:固定课程

于 2014-02-22T17:17:39.090 回答
0

您可以将其转换为 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
于 2014-02-22T17:16:09.440 回答