From d91005f0d149124749ad6cc98bc42b4111900963 Mon Sep 17 00:00:00 2001 From: David Cantrell Date: Fri, 26 Sep 2008 16:03:53 -1000 Subject: Add a address check capability for IPv4 and IPv6 addresses. Add the -c, --check argument which enables address validation. The ipcalc program will exit with 0 if the address is valid or 1 if it is invalid, for the specified family. Add the -4, --ipv4 argument to specify the IPv4 address family. Add the -6, --ipv6 argument to specify the IPv6 address family. Ensure that the IPv6 family argument is invalid with the IPv4-only show arguments (broadcast, network, netmask, prefix). --- src/ipcalc.c | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'src/ipcalc.c') diff --git a/src/ipcalc.c b/src/ipcalc.c index 23a72207..ede86145 100644 --- a/src/ipcalc.c +++ b/src/ipcalc.c @@ -201,6 +201,7 @@ int main(int argc, const char **argv) { int showBroadcast = 0, showPrefix = 0, showNetwork = 0; int showHostname = 0, showNetmask = 0; int beSilent = 0; + int doCheck = 0, familyIPv4 = 1, familyIPv6 = 0; int rc; poptContext optCon; char *ipStr, *prefixStr, *netmaskStr, *hostName, *chptr; @@ -209,6 +210,12 @@ int main(int argc, const char **argv) { int prefix = 0; char errBuf[250]; struct poptOption optionsTable[] = { + { "check", 'c', 0, &doCheck, 0, + "Validate IP address for specified address family", }, + { "ipv4", '4', 0, &familyIPv4, 0, + "IPv4 address family", }, + { "ipv6", '6', 0, &familyIPv6, 0, + "IPv6 address family", }, { "broadcast", 'b', 0, &showBroadcast, 0, "Display calculated broadcast address", }, { "hostname", 'h', 0, &showHostname, 0, @@ -228,6 +235,21 @@ int main(int argc, const char **argv) { optCon = poptGetContext("ipcalc", argc, argv, optionsTable, 0); poptReadDefaultConfig(optCon, 1); + if (familyIPv4 && familyIPv6) { + if (!beSilent) { + fprintf(stderr, "ipcalc: cannot specify both address families\n"); + } + return 1; + } + + if (familyIPv6 && + (showBroadcast || showNetmask || showNetwork || showPrefix)) { + if (!beSilent) { + fprintf(stderr, "ipcalc: unable to show setting for IPv6\n"); + } + return 1; + } + if ((rc = poptGetNextOpt(optCon)) < -1) { if (!beSilent) { fprintf(stderr, "ipcalc: bad argument %s: %s\n", @@ -246,6 +268,26 @@ int main(int argc, const char **argv) { return 1; } + if (doCheck) { + if (familyIPv4) { + struct in_addr tmpaddr; + memset(&tmpaddr, 0, sizeof(tmpaddr)); + + if (inet_pton(AF_INET, ipStr, &tmpaddr) >= 1) + return 0; + else + return 1; + } else if (familyIPv6) { + struct in6_addr tmpaddr; + memset(&tmpaddr, 0, sizeof(tmpaddr)); + + if (inet_pton(AF_INET6, ipStr, &tmpaddr) >= 1) + return 0; + else + return 1; + } + } + if (strchr(ipStr,'/') != NULL) { prefixStr = strchr(ipStr, '/') + 1; prefixStr--; -- cgit v1.2.1