user3178556 user3178556 - 1 month ago 6
C# Question

Console window closes immediately when I run the program

It's just a simple IP mask calculator, but when I run the program I want it to display the broadcast and network address, but the window closes immediately when I run it. Can someone tell me what I'm doing wrong?

namespace ConsoleApplication5
{
public static class Project3
{
static void Main(string[] args)
{
Console.WriteLine("Hello");
var ip1 = IPAddress.Parse("192.168.0.1");
var ip2 = IPAddress.Parse("192.168.1.40");
var mask = IPAddress.Parse("255.255.255.0");
bool inSameNet = ip1.IsInSameSubnet(ip2, mask);
IPAddress broadcast = GetBroadcastAddress(ip2, mask);
IPAddress net = GetNetworkAddress(ip2, mask);
Console.WriteLine(broadcast);
Console.WriteLine(net);
}
public static IPAddress GetBroadcastAddress(this IPAddress address, IPAddress subnetMask)
{
byte[] addressBytes = address.GetAddressBytes();
byte[] subnetMaskBytes = subnetMask.GetAddressBytes();

if (addressBytes.Length != subnetMaskBytes.Length)
throw new ArgumentException("No Match.");

byte[] broadcastAddress = new byte[addressBytes.Length];
for (int i = 0; i < broadcastAddress.Length; i++)
{
broadcastAddress[i] = (byte)(addressBytes[i] | (subnetMaskBytes[i] ^ 255));
}
return new IPAddress(broadcastAddress);
}

public static IPAddress GetNetworkAddress(this IPAddress address, IPAddress subnetMask)
{
byte[] netAddressBytes = address.GetAddressBytes();
byte[] subnetMaskBytes = subnetMask.GetAddressBytes();

if (netAddressBytes.Length != subnetMaskBytes.Length)
throw new ArgumentException("No match.");

byte[] broadcastAddress = new byte[netAddressBytes.Length];
for (int i = 0; i < broadcastAddress.Length; i++)
{
broadcastAddress[i] = (byte)(netAddressBytes[i] & (subnetMaskBytes[i]));
}
return new IPAddress(broadcastAddress);
}

public static bool IsInSameSubnet(this IPAddress address2, IPAddress address, IPAddress subnetMask)
{
IPAddress network1 = address.GetNetworkAddress(subnetMask);
IPAddress network2 = address2.GetNetworkAddress(subnetMask);

return network1.Equals(network2);
}
}
}

Answer

Add Console.ReadKey() at the end of main method to make program wait for a keypress

static void Main(string[] args)
    {
        Console.WriteLine("Hello");
        var ip1 = IPAddress.Parse("192.168.0.1");
        var ip2 = IPAddress.Parse("192.168.1.40");
        var mask = IPAddress.Parse("255.255.255.0");
        bool inSameNet = ip1.IsInSameSubnet(ip2, mask);
        IPAddress broadcast = GetBroadcastAddress(ip2, mask);
        IPAddress net = GetNetworkAddress(ip2, mask);
        Console.WriteLine(broadcast);
        Console.WriteLine(net);
        Console.ReadKey();
    }