• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lduchosal / ipnetwork / 809

17 Aug 2025 08:25AM UTC coverage: 93.223% (-1.0%) from 94.226%
809

push

appveyor

web-flow
Chore: cleanup, breaking changes, enum, tryparse, exception, static ListIPAddress (#363)

* Chore: huge cleanup, enum, tryparse, exception, static ListIPAddress, important changes : IPNetwork comparison and sort order have change to reflect expected behavoir
* Fix: obsolete enums
* Fix: network sorting and member comparison
* Chore: upgrade version number 3.3

1802 of 1933 relevant lines covered (93.22%)

726934.37 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.15
/src/ConsoleApplication/Program.cs
1
// <copyright file="Program.cs" company="IPNetwork">
2
// Copyright (c) IPNetwork. All rights reserved.
3
// </copyright>
4

5
namespace System.Net;
6

7
using Gnu.Getopt;
8
using System.Collections.Generic;
9
using System.Diagnostics;
10
using System.IO;
11
using System.Numerics;
12
using System.Reflection;
13

14
/// <summary>
15
/// Console app for IPNetwork.
16
/// </summary>
17
public static class Program
18
{
19
    private static readonly Dictionary<int, ArgParsed> Args = new ();
1✔
20

21
    private static readonly ArgParsed[] ArgsList =
1✔
22
    [
1✔
23
        new ArgParsed('i', (ac, _) => { ac.IPNetwork = true; }),
3✔
24
        new ArgParsed('n', (ac, _) => { ac.Network = true; }),
6✔
25
        new ArgParsed('m', (ac, _) => { ac.Netmask = true; }),
6✔
26
        new ArgParsed('c', (ac, _) => { ac.Cidr = true; }),
6✔
27
        new ArgParsed('b', (ac, _) => { ac.Broadcast = true; }),
6✔
28
        new ArgParsed('f', (ac, _) => { ac.FirstUsable = true; }),
6✔
29
        new ArgParsed('l', (ac, _) => { ac.LastUsable = true; }),
6✔
30
        new ArgParsed('u', (ac, _) => { ac.Usable = true; }),
6✔
31
        new ArgParsed('t', (ac, _) => { ac.Total = true; }),
×
32
        new ArgParsed('w', (ac, _) => { ac.Action = Action.Supernet; }),
3✔
33
        new ArgParsed('W', (ac, _) => { ac.Action = Action.WideSupernet; }),
×
34
        new ArgParsed('h', (ac, _) => { ac.Action = Action.Usage; }),
×
35
        new ArgParsed('x', (ac, _) => { ac.Action = Action.ListIPAddress; }),
3✔
36
        new ArgParsed('?', (_, _) => { }),
4✔
37
        new ArgParsed('D', (ac, _) => { ac.CidrParse = CidrParse.Default; }),
×
38
        new ArgParsed('d', (ac, arg) =>
1✔
39
        {
2✔
40
            if (!IPNetwork2.TryParseCidr(arg, Sockets.AddressFamily.InterNetwork, out byte? cidr))
2✔
41
            {
×
42
                Console.WriteLine("Invalid cidr {0}", cidr);
×
43
                ac.Action = Action.Usage;
×
44
                return;
×
45
            }
1✔
46

1✔
47
            ac.CidrParse = CidrParse.Value;
2✔
48
            ac.CidrParsed = (byte)cidr!;
2✔
49
        }),
2✔
50
        new ArgParsed('s', (ac, arg) =>
1✔
51
        {
1✔
52
            if (!IPNetwork2.TryParseCidr(arg, Sockets.AddressFamily.InterNetwork, out byte? cidr))
1✔
53
            {
×
54
                Console.WriteLine("Invalid cidr {0}", cidr);
×
55
                ac.Action = Action.Usage;
×
56
                return;
×
57
            }
1✔
58

1✔
59
            ac.Action = Action.Subnet;
1✔
60
            ac.SubnetCidr = (byte)cidr!;
1✔
61
        }),
1✔
62
        new ArgParsed('C', (ac, arg) =>
1✔
63
        {
1✔
64
            if (!TryParseIPNetwork(arg, ac.CidrParse, ac.CidrParsed, out IPNetwork2 ipnetwork))
1✔
65
            {
×
66
                Console.WriteLine($"Unable to parse ipnetwork {arg}", arg);
×
67
                ac.Action = Action.Usage;
×
68
                return;
×
69
            }
1✔
70

1✔
71
            ac.Action = Action.ContainNetwork;
1✔
72
            ac.ContainNetwork = ipnetwork;
1✔
73
        }),
1✔
74
        new ArgParsed('o', (ac, arg) =>
1✔
75
        {
1✔
76
            if (!TryParseIPNetwork(arg, ac.CidrParse, ac.CidrParsed, out IPNetwork2 ipnetwork))
1✔
77
            {
×
78
                Console.WriteLine("Unable to parse ipnetwork {0}", arg);
×
79
                ac.Action = Action.Usage;
×
80
                return;
×
81
            }
1✔
82

1✔
83
            ac.Action = Action.OverlapNetwork;
1✔
84
            ac.OverlapNetwork = ipnetwork;
1✔
85
        }),
1✔
86
        new ArgParsed('S', (ac, arg) =>
1✔
87
        {
1✔
88
            if (!TryParseIPNetwork(arg, ac.CidrParse, ac.CidrParsed, out IPNetwork2 ipnetwork))
1✔
89
            {
×
90
                Console.WriteLine("Unable to parse ipnetwork {0}", arg);
×
91
                ac.Action = Action.Usage;
×
92
                return;
×
93
            }
1✔
94

1✔
95
            ac.Action = Action.SubtractNetwork;
1✔
96
            ac.SubtractNetwork = ipnetwork;
1✔
97
        })
1✔
98
    ];
1✔
99

100
    /// <summary>
101
    /// Program entry point.
102
    /// </summary>
103
    /// <param name="args">program arguments.</param>
104
    public static void Main(string[] args)
105
    {
11✔
106
        ProgramContext ac = ParseArgs(args);
11✔
107

108
        switch (ac.Action)
11✔
109
        {
110
            case Action.Subnet:
111
                SubnetNetworks(ac);
1✔
112
                break;
1✔
113
            case Action.Supernet:
114
                SupernetNetworks(ac);
1✔
115
                break;
1✔
116
            case Action.WideSupernet:
117
                WideSupernetNetworks(ac);
×
118
                break;
×
119
            case Action.PrintNetworks:
120
                PrintNetworks(ac);
5✔
121
                break;
5✔
122
            case Action.ContainNetwork:
123
                ContainNetwork(ac);
1✔
124
                break;
1✔
125
            case Action.OverlapNetwork:
126
                OverlapNetwork(ac);
1✔
127
                break;
1✔
128
            case Action.ListIPAddress:
129
                ListIPAddress(ac);
×
130
                break;
×
131
            case Action.SubtractNetwork:
132
                SubtractNetwork(ac);
1✔
133
                break;
1✔
134
            default:
135
                Usage();
1✔
136
                break;
1✔
137
        }
138
    }
11✔
139

140
    private static void ListIPAddress(ProgramContext ac)
141
    {
×
142
        foreach (IPNetwork2 ipnetwork in ac.Networks)
×
143
        {
×
144
            foreach (IPAddress ipaddress in ipnetwork.ListIPAddress())
×
145
            {
×
146
                Console.WriteLine("{0}", ipaddress.ToString());
×
147
            }
×
148
        }
×
149
    }
×
150
    
151
    private static void SubtractNetwork(ProgramContext ac)
152
    {
1✔
153
        foreach (IPNetwork2 ipnetwork in ac.Networks)
13✔
154
        {
5✔
155
            foreach (IPNetwork2 subtracted in ipnetwork.Subtract(ac.SubtractNetwork))
25✔
156
            {
5✔
157
                Console.WriteLine("{0}", subtracted);
5✔
158
            }
5✔
159
        }
5✔
160
    }
1✔
161
    
162
    private static void ContainNetwork(ProgramContext ac)
163
    {
1✔
164
        foreach (IPNetwork2 ipnetwork in ac.Networks)
5✔
165
        {
1✔
166
            bool contain = ac.ContainNetwork.Contains(ipnetwork);
1✔
167
            Console.WriteLine("{0} contains {1} : {2}", ac.ContainNetwork, ipnetwork, contain);
1✔
168
        }
1✔
169
    }
1✔
170

171
    private static void OverlapNetwork(ProgramContext ac)
172
    {
1✔
173
        foreach (IPNetwork2 ipnetwork in ac.Networks)
5✔
174
        {
1✔
175
            bool overlap = ac.OverlapNetwork.Overlap(ipnetwork);
1✔
176
            Console.WriteLine("{0} overlaps {1} : {2}", ac.OverlapNetwork, ipnetwork, overlap);
1✔
177
        }
1✔
178
    }
1✔
179

180
    private static void WideSupernetNetworks(ProgramContext ac)
181
    {
×
182
        if (!IPNetwork2.TryWideSubnet(ac.Networks, out IPNetwork2 widesubnet))
×
183
        {
×
184
            Console.WriteLine("Unable to wide subnet these networks");
×
185
        }
×
186

187
        PrintNetwork(ac, widesubnet);
×
188
    }
×
189

190
    private static void SupernetNetworks(ProgramContext ac)
191
    {
1✔
192
        if (!IPNetwork2.TrySupernet(ac.Networks, out IPNetwork2[] supernet))
1✔
193
        {
×
194
            Console.WriteLine("Unable to supernet these networks");
×
195
        }
×
196

197
        PrintNetworks(ac, supernet, supernet.Length);
1✔
198
    }
1✔
199

200
    private static void SubnetNetworks(ProgramContext ac)
201
    {
1✔
202
        BigInteger i = 0;
1✔
203
        foreach (IPNetwork2 ipnetwork in ac.Networks)
5✔
204
        {
1✔
205
            i++;
1✔
206
            int networkLength = ac.Networks.Length;
1✔
207
            if (!ipnetwork.TrySubnet(ac.SubnetCidr, out IPNetworkCollection ipnetworks))
1✔
208
            {
×
209
                Console.WriteLine("Unable to subnet ipnetwork {0} into cidr {1}", ipnetwork, ac.SubnetCidr);
×
210
                PrintSeparator(networkLength, i);
×
211
                continue;
×
212
            }
213

214
            PrintNetworks(ac, ipnetworks, ipnetworks.Count);
1✔
215
            PrintSeparator(networkLength, i);
1✔
216
        }
1✔
217
    }
1✔
218

219
    private static void PrintSeparator(BigInteger max, BigInteger index)
220
    {
270✔
221
        if (max > 1 && index != max)
270✔
222
        {
262✔
223
            Console.WriteLine("--");
262✔
224
        }
262✔
225
    }
270✔
226
    
227
    private static void PrintNetworks(ProgramContext ac, IEnumerable<IPNetwork2> ipnetworks, BigInteger networkLength)
228
    {
2✔
229
        int i = 0;
2✔
230
        foreach (IPNetwork2 ipn in ipnetworks)
524✔
231
        {
259✔
232
            i++;
259✔
233
            PrintNetwork(ac, ipn);
259✔
234
            PrintSeparator(networkLength, i);
259✔
235
        }
259✔
236
    }
2✔
237
    
238
    private static void PrintNetworks(ProgramContext ac)
239
    {
5✔
240
        int i = 0;
5✔
241
        foreach (IPNetwork2 ipnetwork in ac.Networks)
35✔
242
        {
10✔
243
            i++;
10✔
244
            PrintNetwork(ac, ipnetwork);
10✔
245
            PrintSeparator(ac.Networks.Length, i);
10✔
246
        }
10✔
247
    }
5✔
248

249
    private static void PrintNetwork(ProgramContext ac, IPNetwork2 ipn)
250
    {
269✔
251
        using var sw = new StringWriter();
269✔
252
        if (ac.IPNetwork)
269✔
253
        {
267✔
254
            sw.WriteLine("IPNetwork   : {0}", ipn);
267✔
255
        }
267✔
256

257
        if (ac.Network)
269✔
258
        {
263✔
259
            sw.WriteLine("Network     : {0}", ipn.Network.ToString());
263✔
260
        }
263✔
261

262
        if (ac.Netmask)
269✔
263
        {
263✔
264
            sw.WriteLine("Netmask     : {0}", ipn.Netmask.ToString());
263✔
265
        }
263✔
266

267
        if (ac.Cidr)
269✔
268
        {
263✔
269
            sw.WriteLine("Cidr        : {0}", ipn.Cidr);
263✔
270
        }
263✔
271

272
        if (ac.Broadcast)
269✔
273
        {
263✔
274
            sw.WriteLine("Broadcast   : {0}", ipn.Broadcast.ToString());
263✔
275
        }
263✔
276

277
        if (ac.FirstUsable)
269✔
278
        {
263✔
279
            sw.WriteLine("FirstUsable : {0}", ipn.FirstUsable.ToString());
263✔
280
        }
263✔
281

282
        if (ac.LastUsable)
269✔
283
        {
263✔
284
            sw.WriteLine("LastUsable  : {0}", ipn.LastUsable.ToString());
263✔
285
        }
263✔
286

287
        if (ac.Usable)
269✔
288
        {
263✔
289
            sw.WriteLine("Usable      : {0}", ipn.Usable);
263✔
290
        }
263✔
291

292
        if (ac.Total)
269✔
293
        {
261✔
294
            sw.WriteLine("Total       : {0}", ipn.Total);
261✔
295
        }
261✔
296

297
        Console.Write(sw.ToString());
269✔
298
    }
538✔
299

300
    static Program()
301
    {
1✔
302
        foreach (ArgParsed ap in ArgsList)
43✔
303
        {
20✔
304
            Args.Add(ap.Arg, ap);
20✔
305
        }
20✔
306
    }
1✔
307

308
    private static ProgramContext ParseArgs(string[] args)
309
    {
11✔
310
        int c;
311
        var g = new Getopt("ipnetwork", args, "inmcbfltud:Dhs:wWxC:o:S:");
11✔
312
        var ac = new ProgramContext();
11✔
313

314
        while ((c = g.getopt()) != -1)
36✔
315
        {
25✔
316
            string optArg = g.Optarg;
25✔
317
            Args[c].Run(ac, optArg);
25✔
318
        }
25✔
319

320
        var ipnetworks = new List<string>();
11✔
321
        for (int i = g.Optind; i < args.Length; i++)
72✔
322
        {
25✔
323
            if (!string.IsNullOrEmpty(args[i]))
25✔
324
            {
25✔
325
                ipnetworks.Add(args[i]);
25✔
326
            }
25✔
327
        }
25✔
328

329
        ac.NetworksString = ipnetworks.ToArray();
11✔
330
        ParseIPNetworks(ac);
11✔
331

332
        if (ac.Networks.Length == 0)
11✔
333
        {
1✔
334
            Console.WriteLine("Provide at least one ipnetwork");
1✔
335
            ac.Action = Action.Usage;
1✔
336
        }
1✔
337

338
        if (ac.Action == Action.Supernet
11✔
339
            && ipnetworks.Count < 2)
11✔
340
        {
×
341
            Console.WriteLine("Supernet action required at least two ipnetworks");
×
342
            ac.Action = Action.Usage;
×
343
        }
×
344

345
        if (ac.Action == Action.WideSupernet
11✔
346
            && ipnetworks.Count < 2)
11✔
347
        {
×
348
            Console.WriteLine("WideSupernet action required at least two ipnetworks");
×
349
            ac.Action = Action.Usage;
×
350
        }
×
351

352
        if (PrintNoValue(ac))
11✔
353
        {
8✔
354
            PrintAll(ac);
8✔
355
        }
8✔
356

357
        if (g.Optind == 0)
11✔
358
        {
3✔
359
            PrintAll(ac);
3✔
360
        }
3✔
361

362
        return ac;
11✔
363
    }
11✔
364

365
    private static void ParseIPNetworks(ProgramContext ac)
366
    {
11✔
367
        var ipnetworks = new List<IPNetwork2>();
11✔
368
        foreach (string ips in ac.NetworksString)
83✔
369
        {
25✔
370
            if (!TryParseIPNetwork(ips, ac.CidrParse, ac.CidrParsed, out IPNetwork2 ipnetwork))
25✔
371
            {
1✔
372
                Console.WriteLine("Unable to parse ipnetwork {0}", ips);
1✔
373
                continue;
1✔
374
            }
375

376
            ipnetworks.Add(ipnetwork);
24✔
377
        }
24✔
378

379
        ac.Networks = ipnetworks.ToArray();
11✔
380
    }
11✔
381

382
    private static bool TryParseIPNetwork(string ip, CidrParse cidrParse, byte cidr, out IPNetwork2 ipn)
383
    {
28✔
384
        IPNetwork2 ipnetwork = null;
28✔
385
        switch (cidrParse)
28✔
386
        {
387
            case CidrParse.Default when !IPNetwork2.TryParse(ip, out ipnetwork):
×
388
                ipn = null;
×
389
                return false;
×
390
            case CidrParse.Value:
391
            {
28✔
392
                if (!IPNetwork2.TryParse(ip, cidr, out ipnetwork)
28✔
393
                    && !IPNetwork2.TryParse(ip, out ipnetwork))
28✔
394
                {
1✔
395
                    ipn = null;
1✔
396
                    return false;
1✔
397
                }
398

399
                break;
27✔
400
            }
401
        }
402

403
        ipn = ipnetwork;
27✔
404
        return true;
27✔
405
    }
28✔
406

407
    private static bool PrintNoValue(ProgramContext ac)
408
    {
11✔
409
        ArgumentNullException.ThrowIfNull(ac);
11✔
410

411
        return !ac.IPNetwork 
11✔
412
               && !ac.Network 
11✔
413
               && !ac.Netmask 
11✔
414
               && !ac.Cidr 
11✔
415
               && !ac.Broadcast 
11✔
416
               && !ac.FirstUsable 
11✔
417
               && !ac.LastUsable 
11✔
418
               && !ac.Total 
11✔
419
               && !ac.Usable;
11✔
420
    }
11✔
421

422
    private static void PrintAll(ProgramContext ac)
423
    {
11✔
424
        ArgumentNullException.ThrowIfNull(ac);
11✔
425

426
        ac.IPNetwork = true;
11✔
427
        ac.Network = true;
11✔
428
        ac.Netmask = true;
11✔
429
        ac.Cidr = true;
11✔
430
        ac.Broadcast = true;
11✔
431
        ac.FirstUsable = true;
11✔
432
        ac.LastUsable = true;
11✔
433
        ac.Usable = true;
11✔
434
        ac.Total = true;
11✔
435
    }
11✔
436

437
    private static void Usage()
438
    {
1✔
439
        Assembly assembly = Assembly.GetEntryAssembly()
1✔
440
                            ?? Assembly.GetExecutingAssembly()
1✔
441
            ;
1✔
442
        var fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
1✔
443
        string version = fvi.FileVersion;
1✔
444

445
        Console.WriteLine(
1✔
446
            "Usage: ipnetwork [-inmcbflu] [-d cidr|-D] [-h|-s cidr|-S network|-w|-W|-x|-C network|-o network] networks ...");
1✔
447
        Console.WriteLine("Version: {0}", version);
1✔
448
        Console.WriteLine();
1✔
449
        Console.WriteLine("Print options");
1✔
450
        Console.WriteLine("\t-i : network");
1✔
451
        Console.WriteLine("\t-n : network address");
1✔
452
        Console.WriteLine("\t-m : netmask");
1✔
453
        Console.WriteLine("\t-c : cidr");
1✔
454
        Console.WriteLine("\t-b : broadcast");
1✔
455
        Console.WriteLine("\t-f : first usable ip address");
1✔
456
        Console.WriteLine("\t-l : last usable ip address");
1✔
457
        Console.WriteLine("\t-u : number of usable ip addresses");
1✔
458
        Console.WriteLine("\t-t : total number of ip addresses");
1✔
459
        Console.WriteLine();
1✔
460
        Console.WriteLine("Parse options");
1✔
461
        Console.WriteLine("\t-d cidr : use cidr if not provided (default /32)");
1✔
462
        Console.WriteLine("\t-D      : IPv4 only - use default cidr (ClassA/8, ClassB/16, ClassC/24)");
1✔
463
        Console.WriteLine();
1✔
464
        Console.WriteLine("Actions");
1✔
465
        Console.WriteLine("\t-h         : help message");
1✔
466
        Console.WriteLine("\t-s cidr    : split network into cidr subnets");
1✔
467
        Console.WriteLine("\t-w         : supernet networks into smallest possible subnets");
1✔
468
        Console.WriteLine("\t-W         : supernet networks into one single subnet");
1✔
469
        Console.WriteLine("\t-x         : list all ip adresses in networks");
1✔
470
        Console.WriteLine("\t-C network : network contain networks");
1✔
471
        Console.WriteLine("\t-o network : network overlap networks");
1✔
472
        Console.WriteLine("\t-S network : subtract network from networks");
1✔
473
        Console.WriteLine(string.Empty);
1✔
474
        Console.WriteLine("networks  : one or more network addresses ");
1✔
475
        Console.WriteLine(
1✔
476
            "            (1.2.3.4 10.0.0.0/8 10.0.0.0/255.0.0.0 2001:db8::/32 2001:db8:1:2:3:4:5:6/128 )");
1✔
477
    }
1✔
478
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc