-4

I am wondering how to write all the possible combinations of a number with 3 decimals in it.

As you might have guessed I am using this for IP addresses, so I need the numbers for the 4 decimal places to be between 0 and 255. Is there any way I can write in a console application every combination of a 4 decimal place number (0.0.0.0 - 255.255.255.255)? If this can be done, a reply would be awesome. Thanks for reading!

Jkaay
  • 11
  • 4
  • 2
    Everything in the world is doable if we try. So go ahead and give it a try, post your efforts here, and then come up with specific issue. – Nikhil Vartak May 13 '17 at 21:40
  • Thanks for the reply. I was messing around with this project for awhile, but didn't know what code sample to post here because I was unsure what could be relevant to the question. – Jkaay May 13 '17 at 21:42

2 Answers2

1

Yes, you can achieve this with simple nested for loops like this:

public class Program
{
    public static void Main(string[] args)
    {
        for (int a = 0; a < 256; a++)
        {
           for (int b = 0; b < 256; b++)
           {
               for (int c = 0; c < 256; c++) 
               {
                   for (int d = 0; d < 256; d++)
                   {
                       string ipAddress = string.Format("{0}.{1}.{2}.{3}", a, b, c, d);
                       Console.WriteLine(ipAddress);
                   }
               }
           }
        }
    }
}
xcvd
  • 666
  • 1
  • 5
  • 13
0

Since you can convert an IP4 address to integer, you could do this in one for loop:

for (uint i = 0; i <= 4294967295; i++)
{
    byte[] bytes = BitConverter.GetBytes(i);
    Array.Reverse(bytes);
    string ipAddress = new IPAddress(bytes).ToString();
    Console.WriteLine(ipAddress);
}
Community
  • 1
  • 1
Filburt
  • 16,221
  • 12
  • 59
  • 107