Search code examples
prologdcg

Prolog Definite Clause Grammar program for IPv4 address


I'm currently trying to set up a little program for accepting IPv4 dotted quad strings in SWI Prolog using DCGs (getting out of the comfort zone during holidays? yes I can!). This is probably going to take me another hour or so, but maybe someone of the readership has one ready already. In which case I can attack IPv6 address strings.


Solution

  • I'll try to answer on SWISH, on this snippet

    Here is the code, in case the link is volatile...

    :- use_module(library(dcg/basics)).
    
    atom_ipv4(A, IPV4) :- atom_codes(A, Cs), phrase(ipv4(IPV4), Cs).
    
    ipv4(D) -->
        dotted(D).
    ipv4(range(D, R)) -->
        dotted(D), "/", integer(R).
    
    dotted(address(A, B, C, D)) -->
        octet(A), ".", octet(B), ".", octet(C), ".", octet(D).
    
    octet(A) --> integer(A), {A < 256}.
    

    Note: surely the specification is more complex than that captured by this snippet, since it allows hexadecimal, and more... my purpose what to point out the availability of library(dcg/basics)