C
C
Chvalov2014-10-15 19:52:37
Programming
Chvalov, 2014-10-15 19:52:37

How to get list of ip from range in C#?

There is a form on it there are 4 elements Edit1 (Start range) Edit2 (End range) Edit3 (IP list output)
Button1 start button.
How can I make it show a list of ip-shniks from the range.
No matter how I twisted it, nothing happens, but I tried it from the console source:

using System;
using System.Linq;
using System.Net;
 
namespace _1037965
{
    class Program
    {
        static void Main()
        {
            var beginIp = GetIp("Введите начальный ip: ");
            var endIp = GetIp("Введите конечный ip: ");
            for (var value = beginIp; value <= endIp; value++)
            {
                var ipBytes = BitConverter.GetBytes(value).ToList();
                ipBytes.Reverse();
                var ip = new IPAddress(ipBytes.ToArray());
                Console.WriteLine(ip);
            }
            Console.ReadLine();
        }
 
        private static uint GetIp(string text)
        {
            Console.Write(text);
            string strBeginIp = Console.ReadLine();
            var bytesIp = IPAddress.Parse(strBeginIp).GetAddressBytes().ToList();
            bytesIp.Reverse();
            return BitConverter.ToUInt32(bytesIp.ToArray(), 0);
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
StrangeAttractor, 2014-10-15
@StrangeAttractor

Try like this:

private static List<IPAddress> IPAddressesRange(IPAddress firstIPAddress, IPAddress lastIPAddress)
{
    var firstIPAddressAsBytesArray = firstIPAddress.GetAddressBytes();

    var lastIPAddressAsBytesArray = lastIPAddress.GetAddressBytes();

    Array.Reverse(firstIPAddressAsBytesArray);

    Array.Reverse(lastIPAddressAsBytesArray);

    var firstIPAddressAsInt = BitConverter.ToInt32(firstIPAddressAsBytesArray, 0);

    var lastIPAddressAsInt = BitConverter.ToInt32(lastIPAddressAsBytesArray, 0);

    var ipAddressesInTheRange = new List<IPAddress>();

    for (var i = firstIPAddressAsInt; i <= lastIPAddressAsInt; i++)
    {
        var bytes = BitConverter.GetBytes(i);

        var newIp = new IPAddress(new[] {bytes[3], bytes[2], bytes[1], bytes[0]});

        ipAddressesInTheRange.Add(newIp);
    }

    return ipAddressesInTheRange;
}

You can convert a text string into an IPAddress (to be input to the above function) like this:
(it is assumed that the ipString variable is of type string and contains the IP address in textual notation).
Usage example (when button1 is pressed, we calculate the range from 192.168.0.1 to 192.168.0.10 and put the second address from the received range in the form header):
private void button1_Click(object sender, EventArgs e)
{
    var first = "192.168.0.1";

    var last = "192.168.0.10";

    var range = IPAddressesRange(IPAddress.Parse(first), IPAddress.Parse(last));

    Text = range[1].ToString();
}

I never wrote console programs in C # (somehow it happened historically, I wrote under the console in other languages), so I suggest you debug the issue of data entry yourself, and what to do next when you received the first and last IP in string format, I hope you understand their last example (if not, let me know).
UPDATE: Because the questioner, judging by the comments, did not help, I add the full code of the working WinForms program:
using System;
using System.Collections.Generic;
using System.Net;
using System.Windows.Forms;

namespace IpRange
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void goButton_Click(object sender, EventArgs e)
        {
            IPAddress firstIpAddress;

            IPAddress lastIpAddress;

            if (String.IsNullOrWhiteSpace(firstIpAddressTextBox.Text))
            {
                MessageBox.Show("Не задан начальный IP-адрес диапазона", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            if (String.IsNullOrWhiteSpace(lastIpAddressTextBox.Text))
            {
                MessageBox.Show("Не задан начальный IP-адрес диапазона", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            try
            {
                firstIpAddress = IPAddress.Parse(firstIpAddressTextBox.Text);
            }
            catch (FormatException)
            {
                MessageBox.Show("Неправильно задан финальный IP-адрес диапазона", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            try
            {
                lastIpAddress = IPAddress.Parse(lastIpAddressTextBox.Text);
            }
            catch (FormatException)
            {
                MessageBox.Show("Неправильно задан финальный IP-адрес диапазона", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            var range = IPAddressesRange(firstIpAddress, lastIpAddress);

            wholeRangeListBox.Items.Clear();

            wholeRangeListBox.Items.AddRange(range.ToArray());

            // Или так (*вместо* предыдущей строчки - ту убрать, эту разкомментировать):
            // foreach (var ipAddress in range) wholeRangeListBox.Items.Add(ipAddress);
        }

        private static List<IPAddress> IPAddressesRange(IPAddress firstIPAddress, IPAddress lastIPAddress)
        {
            var firstIPAddressAsBytesArray = firstIPAddress.GetAddressBytes();

            var lastIPAddressAsBytesArray = lastIPAddress.GetAddressBytes();

            Array.Reverse(firstIPAddressAsBytesArray);

            Array.Reverse(lastIPAddressAsBytesArray);

            var firstIPAddressAsInt = BitConverter.ToInt32(firstIPAddressAsBytesArray, 0);

            var lastIPAddressAsInt = BitConverter.ToInt32(lastIPAddressAsBytesArray, 0);

            var ipAddressesInTheRange = new List<IPAddress>();

            for (var i = firstIPAddressAsInt; i <= lastIPAddressAsInt; i++)
            {
                var bytes = BitConverter.GetBytes(i);

                var newIp = new IPAddress(new[] {bytes[3], bytes[2], bytes[1], bytes[0]});

                ipAddressesInTheRange.Add(newIp);
            }

            return ipAddressesInTheRange;
        }
    }
}

Please note that the program is "cultivated", which is expressed not only in checking input values ​​for emptiness and handling unexpected input with exceptions, but also in using informative names for elements: I usually rename the main form from Form1 to MainForm, the button is renamed from button1 to goButton , the input textboxes are firstIpAddressTextBox and lastIpAddressTextBox , the output list is wholeRangeListBox - hopefully this won't cause any extra hassle using this code.

S
Sergey, 2014-10-15
Protko @Fesor

An ip address is 4 octets bits (4 bytes), so first cast the IP addresses into an int32. Then a simple increment in a loop.

string from = textEdit1.Text;
string to = textEdit2.Text;
// todo: нужно хэндлить исключения так как пользователь может ввести чушь
int ipFrom = BitConverter.ToInt32(IPAddress.Parse(from).GetAddressBytes(), 0);
int ipTo = BitConverter.ToInt32(IPAddress.Parse(to).GetAddressBytes(), 0);

IEnumerable<int> ipRange = Enumerable.Range(ipFrom, ipTo);

to convert int back to string, you can again do this:
string address = new IPAddress(BitConverter.GetBytes(intAddress)).ToString();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question