C#.net

List all IP s in range using c#.net



Here is the code snippet in c#.net to get all the ip address with in a range.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace WindowsFormsApplication3
{
  public partial class Form1 : Form
  {

      public Form1()
    {
       InitializeComponent();

     }
        private void button1_Click(object sender, EventArgs e)
  {

            IPAddress StartIp = IPAddress.Parse("192.168.0.1");
            IPAddress EndIp = IPAddress.Parse("192.168.0.100");
            GetIPRange(StartIp,EndIp);
        }
        public void GetIPRange(IPAddress startIP, IPAddress endIP)
        {
            uint sIP = ipToUint(startIP.GetAddressBytes());
            uint eIP = ipToUint(endIP.GetAddressBytes());
            while (sIP < eIP)
            {
                IPAddress i= new IPAddress(reverseBytesArray(sIP));
 //The ip address will be there in "i"
                }
                catch
                {
                }
                sIP++;
            }         
       }

        /* reverse byte order in array */

        protected uint reverseBytesArray(uint ip)

        {
            byte[] bytes = BitConverter.GetBytes(ip);
            bytes = bytes.Reverse().ToArray();
            return (uint)BitConverter.ToInt32(bytes, 0);
        }

        /* Convert bytes array to 32 bit long value */

        protected uint ipToUint(byte[] ipBytes)
        {
            ByteConverter bConvert = new ByteConverter();
            uint ipUint = 0;
            int shift = 24; // indicates number of bits left for shifting
            foreach (byte b in ipBytes)
            {
                if (ipUint == 0)
                {
                    ipUint = (uint)bConvert.ConvertTo(b, typeof(uint)) << shift;
                    shift -= 8;
                    continue;
                }
                if (shift >= 8)
                 ipUint += (uint)bConvert.ConvertTo(b, typeof(uint)) << shift;
                else
                    ipUint += (uint)bConvert.ConvertTo(b, typeof(uint));
               shift -= 8;
            }
            return ipUint;
        }
    }

}

Share

Thanks for reading my blog. If you like what I write, why not subscribe to my feed?

If you are busy, I can send the latest post to your email. Just subscribe to my email updates.

 

Enter your email address:

Delivered by FeedBurner

Discussion

No comments for “List all IP s in range using c#.net”

Post a comment