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

99封情书 提交于 2019-11-28 06:58:19

问题


I am trying to convert strings into Inetaddress. I am not trying to resolve hostnames: the strings are ipv4 addresses. Does InetAddress.getByName(String host) work? Or do I have to manually parse it?


回答1:


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.




回答2:


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.




回答3:


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!




回答4:


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.




回答5:


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
      }


来源:https://stackoverflow.com/questions/2309049/is-there-an-easy-way-to-convert-string-to-inetaddress-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!