Is there an easy way to convert String to Inetaddress in Java?

前端 未结 5 371
南旧
南旧 2020-12-20 10:46

I am trying to convert strings into Inetaddress. I am not trying to resolve hostnames: the strings are ipv4 addresses. Does InetAddress.getByName(String h

相关标签:
5条回答
  • 2020-12-20 11:26

    Beware: it seems that parsing an invalid address such as InetAddress.getByName("999.999.999.999") will not result in an exception as one might expect from the documentation's phrase:

    the validity of the address format is checked

    Empirically, I find myself getting an InetAddress instance with the local machine's raw IP address and the invalid IP address as the host name. Certainly this was not what I expected!

    0 讨论(0)
  • 2020-12-20 11:31

    You could try using a regular expression to filter-out non-numeric IP addresses before passing the String to getByName(). Then getByName() will not try name resolution.

    0 讨论(0)
  • 2020-12-20 11:39

    Yes, that will work. The API is very clear on this ("The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address."), and of course you could easily check yourself.

    0 讨论(0)
  • 2020-12-20 11:42

    The open-source IPAddress Java library will validate all standard representations of IPv6 and IPv4 and will do so without DNS lookup. Disclaimer: I am the project manager of that library.

    The following code will do what you are requesting:

         String s = "1.2.3.4";
         try {
                IPAddressString str = new IPAddressString(s);
                IPAddress addr = str.toAddress();
                InetAddress inetAddress = addr.toInetAddress(); //IPv4 or IPv6
                if(addr.isIPv4() || addr.isIPv4Convertible()) {//IPv4 specific
                    IPv4Address ipv4Addr = addr.toIPv4();
                    Inet4Address inetAddr = ipv4Addr.toInetAddress();
                    //use address
                }
          } catch(AddressStringException e) {
                //e.getMessage has validation error
          }
    
    0 讨论(0)
  • 2020-12-20 11:49

    com.google.common.net.InetAddresses.forString(String ipString) is better for this as it will not do a DNS lookup regardless of what string is passed to it.

    0 讨论(0)
提交回复
热议问题