java - Trying to derive IPv4 address from given IPv4-mapped IPv6 address -
my problem statement says can receive either ipv4 address or v4-mapped v6 address inetsocketaddress instance. if v4-mapped v6 address i've derive v4 address , use that.
i reading javadoc of inetaddresses , says:
`technically 1 can create 128bit ipv6 address wire format of "mapped" address, shown above, , transmit in ipv6 packet header. however, java's inetaddress creation methods appear adhere doggedly original intent of "mapped" address: "mapped" addresses return inet4address objects.`
i can determine if received address v4-mapped v6 address using 1 methods library this:
// input inetsocketaddress socketaddress if (inetaddresses.ismappedipv4address(socketaddress.getaddress().gethostaddress())) { system.out.println("this v4 mapped v6 address"); }
as per documentation none of libraries (inetsocketaddress, inetaddress or inetaddresses) provides method deriving ipv4 address such mapped input. mean type-casting inetaddress received inetsocketaddress inet4address sufficient?
inet4address inetaddress = (inet4address) socketaddress.getaddress();
if so, need use inetaddresses.ismappedipv4address? how can determine if casting failed or given address neither valid ipv4 address nor v4-mapped v6 address can throw appropriate exception?
the ipaddress java library supports both ipv4 , ipv6 in polymorphic manner. can accomplish describing here.
firstly, using library, inetsocketaddress can ipaddress:
inetsocketaddress inetsocketaddress = ...; ipaddress addr = ipaddress.from(inetsocketaddress.getaddress());
from there, can check ipv4 or ipv6:
boolean isipv4 = addr.isipv4(); boolean isipv6 = addr.isipv6();
then if ipv6 or ipv6, can use associated subclass. if ipv6, there can check if address ipv4 mapped, ipv4 compatible, , on. if so, can derived ipv4 address. afterwards, can convert java.net type instance.
if(isipv4) { ipv4address ipv4address = addr.toipv4(); inet4address addr = ipv4address.toinetaddress(); ... } else if(isipv6) { ipv6address ipv6address = addr.toipv6(); if(ipv6address.isipv4compatible() || ipv6address.isipv4mapped()) { ipv4address derivedipv4address = ipv6address.getloweripv4address(); inet4address addr = ipv4address.toinetaddress(); ... } }
the javadoc available @ link.
Comments
Post a Comment