Check whether the ipAddress is in private range

前端 未结 4 486
执笔经年
执笔经年 2021-02-07 06:43

How would I check to see whether the ip address is in private category ?

    if(isPrivateIPAddress(ipAddress)) {
                


        
4条回答
  •  终归单人心
    2021-02-07 07:24

    This is a quick hack I generated to test my own address.

    import java.net.InetAddress;
    import java.net.UnknownHostException;
    
    public class LocalAddress {
    
        public static void main(String[] args) {
            InetAddress address = null;
            try {
                address = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                 e.printStackTrace();
            }
            if (address.isSiteLocalAddress()) {
                System.out.println("Site Local Address: " + address.getHostAddress());
            } else {
                System.out.println("Routeable Address: " + address.getHostAddress());
            }
        }
    
    }
    

    EDIT: This code has not been tested for the link local addresses, localhost, or address blocks reserved for documentation. The first two cases have methods that return them. The last is not referenced in the documentation of the class.

提交回复
热议问题