4
$\begingroup$

Is it possible to validate the format of an IP address (say v4)?

I assumed that IPAddress could do this by failing on non-IP inputs but instead one can pass arbitrary strings (and other expressions), eg IPAddress["not-an-IP"].

I'm thinking of analogs of python ipaddress.ip_address and ip_network that raise errors if the input is not valid format.

Alternatively is there a handy regex, ideally to also considers CIDR ranges?

$\endgroup$
2
  • 3
    $\begingroup$ Have you seen this? $\endgroup$ Commented Dec 21, 2021 at 20:46
  • $\begingroup$ Thanks J.M., that looks usable. $\endgroup$ Commented Dec 21, 2021 at 21:23

2 Answers 2

2
$\begingroup$

There might be other ways, but Interpreter["IPAddress"]["www.example.com"] was the first thing that came to mind.

$\endgroup$
0
$\begingroup$

I have used the following in my personal "network functions" package

ConvertIpv4AddressToList::usage="convert from string to list";
ConvertIpv4AddressToList[ipAddress_String] := ToExpression@StringSplit[ipAddress, "."];


Ipv4AddressQ::usage="check if an IPv4 address is in the valid format";
Ipv4AddressQ[ipAddress_String] :=
    Module[
      {decimalNumbers},
      decimalNumbers = ConvertIpv4AddressToList[ipAddress];
      And[
        StringContainsQ[ipAddress, __ ~~ "." ~~ __ ~~ "." ~~ __ ~~ "." ~~ __],
        StringRiffle[decimalNumbers, "."] == ipAddress, (* eg make 1.1.1.01 fail *)
        Length@decimalNumbers == 4,
        Max[decimalNumbers] <= 255,
        Min[decimalNumbers] >= 0,
        VectorQ[decimalNumbers, IntegerQ]
      ]
    ];
$\endgroup$
2
  • 1
    $\begingroup$ Be careful with ToExpression, Ipv4AddressQ @ "Abort[]". You could start with Ipv4AddresQ[ ipAddress_String ? (StringMatchQ[(DigitCharacter | ".") ..]) ] := $\endgroup$
    – Kuba
    Commented Oct 28, 2022 at 7:13
  • $\begingroup$ Good idea thanks $\endgroup$ Commented Oct 28, 2022 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.