IPv6 address validation and canonicalization

What libraries did you use for this? How compatible are they with each other? Or did you write your own parsing procedure?

I am particularly interested in mutually compatible implementations for Java, C ++, Python and JavaScript that support:

  • zero compression (" ::")
  • IPv4 Mapped Addresses (" ::ffff:123.45.67.89")
  • canonization (including in short form, for readability)
  • CIDR netmasks (e.g. " /64" at the end)
+5
source share
11 answers

POSIX inet_pton inet_ntop . CIDR. , , CIDR IPv6 /number _of_bits, .

, , - . , %eth0, , . getaddrinfo , inet_pton .

, , - getaddrinfo inet_ntop canonicalize.

getaddrinfo Windows. inet_pton inet_ntop - . , IPv6- . , 0 - 0s, . IPv4 (.. ::127.0.0.1) ::IPv4 ::ffff:IPv4.

Windows- , , Python Windows inet_pton inet_ntop .

, , , , . IPv6-.

, , Python, C ++. , Java Javascript.

EDIT. getaddrinfo getnameinfo. , inet_pton inet_ntop. , (AI_NUMERICHOST getaddrinfo NI_NUMERCHOST getnameinfo), - DNS-. Windows, , , , . .

+7

Java

InetAddress.getByName(IP)

, IPv6

Sun Propreated API, oK . DNS. ( / , propreated API. , , )

boolean sun.net.util.IPAddressUtil.isIPv6LiteralAddress(String IP)
+5

Java Guava IPv6 ( IPv4) com.google.common.net.InetAddresses. http://goo.gl/RucRU

+5

javascript-ipv6 . v6decode.com.

API:

var address = new v6.Address("::ffff:7b2d:4359/64");

if (address.isValid()) {
   // Do something if the address is valid
}

console.log(address.correctForm());         // "::ffff:7b2d:4359"
console.log(address.canonicalForm());       // "0000:0000:0000:0000:0000:ffff:7b2d:4359"
console.log(address.v4Form());              // "::ffff:123.45.67.89"
console.log(address.subnetMask);            // "64"
console.log(address.possibleAddresses(96)); // "4,294,967,296"
+4

, os - RE , C/++/Java/Python/Perl/ bash/.... python RE startup, RE , re- , .

PAT_IP4 = r'\.'.join([r'(?:\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])']*4)
RE_IP4 = re.compile(PAT_IP4+'$')
RE_IP6 = re.compile(                 '(?:%(hex4)s:){6}%(ls32)s$'
               '|::(?:%(hex4)s:){5}%(ls32)s$'
              '|(?:%(hex4)s)?::(?:%(hex4)s:){4}%(ls32)s$'
'|(?:(?:%(hex4)s:){0,1}%(hex4)s)?::(?:%(hex4)s:){3}%(ls32)s$'
'|(?:(?:%(hex4)s:){0,2}%(hex4)s)?::(?:%(hex4)s:){2}%(ls32)s$'
'|(?:(?:%(hex4)s:){0,3}%(hex4)s)?::%(hex4)s:%(ls32)s$'
'|(?:(?:%(hex4)s:){0,4}%(hex4)s)?::%(ls32)s$'
'|(?:(?:%(hex4)s:){0,5}%(hex4)s)?::%(hex4)s$'
'|(?:(?:%(hex4)s:){0,6}%(hex4)s)?::$'
  % {
'ls32': r'(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|%s)'%PAT_IP4,
'hex4': r'[0-9a-f]{1,4}'
}, re.IGNORECASE)
+2

, , getaddrinfo() , , Linux POSIX. .

Windows getaddrinfo(), XP .

0
0

getaddrinfo , , , canonicalize, getaddrinfo. Python,

import sys, socket;
result = socket.getaddrinfo('0:0::0:1', None);
print "family:%i socktype:%i proto:%i canonname:%s sockaddr:%s"%result[0];

,

family:10 socktype:1 proto:6 canonname: sockaddr:('::1', 0, 0, 0)

CIDR IPv6 , inet6_network (C99).

0

adhoc-, IPv4 IPV6 : ... . , .

#include <cstdio>
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include <sstream>
#include <utility>
#include <cmath>
#include <cstring>
#include <map>
#include <queue>
#include <limits.h>
using namespace std;
bool check6(string s)
{
    for(int i=0;i<s.length();i++)
    {
       if((s[i] < '0' || s[i] > '9') && (s[i] < 'a' || s[i]> 'f') && 
           (s[i] < 'A' || s[i] > 'F'))                       
          return false;
    }
    return true;
}
   bool check4(string s)
   {
      for(int i=0; i< s.length(); i++)
      {
       if(!(s[i]>= '0' && s[i] <= '9'))
          return false;
      }
     stringstream ss(s);
      int e;
      ss >> e;
     if( e < 0 || e > 255 )
      return false;
     else
      return true;
   }

int main()
{
  string s;
  cin>>s;
  vector<string> v;
  int i=0;
  int d=0;
  if((s.find(":")!=std::string::npos || 
         s.find("::")!=std::string::npos)&&  
     s.find(".")==std::string::npos)     
   {
      int x=0;
      while(i< s.length())
      {
          string s1 ="";
          while(i< s.length() && s[i]!= ':')
          {
             s1+= s[i];
             i++;
          }
         if(s1!="")
         v.push_back(s1);
         if((i+1)< s.length() && s[i]==':' && s[i+1]==':')
            x++;
         i++;
         if(i< s.length())
         d++;
     }
      if(x > 1 || d > 7 || v.size() > 8 || (x==1 && d >6))
      {
         cout<<"Not Valid"<<endl;
         return 0;
      }
      else if(d > 2 && v.size() ==0)
      {

         cout<<"Not Valid"<<endl;
         return 0;
      }
      else
      {
         for(int i=0;i< v.size();i++)
         {
             if((v[i]).length() > 4)
             {
                    cout<<"Not Valid"<<endl;
                 return 0;
              }
             else
             {
                if(!check6(v[i]))
                {

                    cout<<"Not Valid"<<endl;
                    return 0;
                }
            }
         }
         cout<<"Valid Ipv6"<<endl;
          return 0;
      }
   }
else if(s.find(":")==std::string::npos && s.find(".")!=std::string::npos)
{
    while(i< s.length())
    {
        string s1="";
        while( i< s.length() && s[i]!='.')
        {
            s1+=s[i];
            i++;
        }
        i++;
        if(i< s.length())
        d++;
        v.push_back(s1);
    }
    if(d > 4 || v.size()> 4)
    {
        cout<<"Not Valid"<<endl;
        return 0;
    }
    else
    {
        for(int i=0;i<v.size();i++)
        {
            if((v[i]).length() > 3)
            {
                cout<<"Not Valid"<<endl;
                return 0;
            }
            if(!check4(v[i]))
            {
                cout<<"Not Valid"<<endl;
                return 0;
            }
        }   
    }
    cout<<"Valid Ipv4"<<endl;
    return 0;
}

        cout<<"Not Valid"<<endl;

return 0;

}

0

Python 3.1 ipaddr lib.

It is still available as a third-party library: py-ipaddr , available on PyPI .

Compression

>>> ipaddr.IPv6Address('0:0::0:1').compressed
'::1'

IPv4 Mapping

>>> ipaddr.IPv6Address('::ffff:123.45.67.89').ipv4_mapped
IPv4Address('123.45.67.89')

Cidr

>>> ipaddr.IPv6Network('::ffff:123.45.67.89/128')
IPv6Network('::ffff:7b2d:4359/128')
-1
source

In C #, I recommend using the IPNetwork library https://github.com/lduchosal/ipnetwork . Starting with version 2, it also supports IPv4 and IPv6.

IPv6

  IPNetwork ipnetwork = IPNetwork.Parse("2001:0db8::/64");

  Console.WriteLine("Network : {0}", ipnetwork.Network);
  Console.WriteLine("Netmask : {0}", ipnetwork.Netmask);
  Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast);
  Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable);
  Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable);
  Console.WriteLine("Usable : {0}", ipnetwork.Usable);
  Console.WriteLine("Cidr : {0}", ipnetwork.Cidr);

Exit

Network : 2001:db8::
Netmask : ffff:ffff:ffff:ffff::
Broadcast : 
FirstUsable : 2001:db8::
LastUsable : 2001:db8::ffff:ffff:ffff:ffff
Usable : 18446744073709551616
Cidr : 64

Good luck

-1
source

All Articles