csharp:获取 DNS、网关、子网掩码、IP

/// <summary>
    /// DNS、网关、子网掩码、IP
    /// 涂聚文 2015
    /// </summary>
    public class IPAddressString
    {
        /// <summary>
        /// IP地址
        /// </summary>
        private string _localAddress;
        /// <summary>
        /// 子网掩码 
        /// </summary>
        private string _ipSubnet;
        /// <summary>
        /// 默认网关
        /// </summary>
        private string _defaultIPGateway;
        /// <summary>
        /// DNS
        /// </summary>
        private string _firstDNS;
        /// <summary>
        /// 备用DNS
        /// </summary>
        private string _secondDNS;
        /// <summary>
        /// 
        /// </summary>
        private string _hostName;
        /// <summary>
        /// 
        /// </summary>
        private string _macname;

        /// <summary>
        /// IP地址
        /// </summary>
        public string LocalAddress
        {
            get { return _localAddress; }
            set { _localAddress = value; }
        }

        /// <summary>
        /// 子网掩码 
        /// </summary>
        public string IpSubnet
        {
            get { return _ipSubnet; }
            set { _ipSubnet = value; }
        }
        /// <summary>
        /// 默认网关
        /// </summary>
        public string DefaultIPGateway
        {
            get { return _defaultIPGateway; }
            set { _defaultIPGateway = value; }
        }
        /// <summary>
        /// DNS
        /// </summary>
        public string FirstDNS
        {
            get { return _firstDNS; }
            set { _firstDNS = value; }
        }
        /// <summary>
        /// 备用DNS
        /// </summary>
        public string SecondDNS
        {
            get { return _secondDNS; }
            set { _secondDNS = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        public string HostName
        {
            get { return _hostName; }
            set { _hostName = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        public string Macname
        {
            get { return _macname; }
            set { _macname = value; }
        }
    }

/// <summary>
        ///获取 DNS、网关、子网掩码、IP
        ///GEOVIN DU
        /// </summary>
        /// <returns></returns>
        public IPAddressString getIp()
        {
            IPAddressString ip = new IPAddressString();
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection nics = mc.GetInstances();
            foreach (ManagementObject nic in nics)
            {
                if (Convert.ToBoolean(nic["ipEnabled"]) == true)
                {
                    // Get IP,SubNetMask,Gateway
                   ip.LocalAddress = (nic["IPAddress"] as string[])[0];
                   ip.IpSubnet = (nic["IPSubnet"] as string[])[0];
                   ip.DefaultIPGateway = (nic["DefaultIPGateway"] as string[])[0];
                   ip.Macname = nic["MacAddress"].ToString();
                   ip.HostName = Dns.GetHostName();//计算机名
                }
            }

            // Get DNS
            NetworkInterface[] ifs = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface netif in ifs)
            {
                IPInterfaceProperties properties = netif.GetIPProperties();
                IPAddressCollection dnses = properties.DnsAddresses;
                if (dnses.Count > 0)
                {
                    int i = 0;
                    foreach (IPAddress ipAddr in dnses)
                    {
                        // Set DNS To DNS TextBox
                        if (i == 0)
                            ip.FirstDNS = ipAddr.ToString();
                        else
                            ip.SecondDNS = ipAddr.ToString();

                        i++;
                    }
                    break;
                }
            }

            return ip;
        }

  测试

 //1
            //IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName()).Where(address => address.AddressFamily == AddressFamily.InterNetwork).First();
            //MessageBox.Show(ip.ToString());


            //2
            //IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            //foreach (IPAddress addr in localIPs)
            //{
            //    if (addr.AddressFamily == AddressFamily.InterNetwork)
            //    {
            //        MessageBox.Show(addr.ToString());
            //    }               
               
            //}

            //3.
            //IPAddress ip = GetIPAddress("dusystem.com");
            //MessageBox.Show(ip.ToString());

            //4.
            //List<string> ips = GetIPAddress(Dns.GetHostName());
            //foreach (string s in ips)
            //{
            //    MessageBox.Show(s.ToString());
            //}
            
            //5
            IPAddressString ip = getIp();
            MessageBox.Show(ip.IpSubnet);

sql server TQ-script

select parsename(replace('1:5:30',':','.'),1)
go
select parsename(replace('1:5:30',':','.'),2)
go
select parsename(replace('1:5:30',':','.'),3)
go

--IP
select parsename(replace('14.152.70.115',':','.'),1)
go
select parsename(replace('14.152.70.115',':','.'),2)
go
select parsename(replace('14.152.70.115',':','.'),3)
go
select parsename(replace('14.152.70.115',':','.'),4)
go

--我们以查找在范围192.0.0.0~192.255.255.255之间的ip地址为条件,具体的sql语句如下:
select * from QQwryIP
where(
	cast(parsename(IPStart, 4) as int) between 192 and 192
and cast(parsename(IPStart, 3) as int) between 0 and 255
and cast(parsename(IPStart, 2) as int) between 0 and 255
and cast(parsename(IPStart, 1) as int) between 0 and 255
)
go




--字符转数字
if   exists   (select   *   from   dbo.sysobjects   where   id   =   object_id(N'[dbo].[fn_IPtoInt]')   and   xtype   in   (N'FN',   N'IF',   N'TF'))  
  drop   function   [dbo].[fn_IPtoInt]  
  GO  
  CREATE   FUNCTION   [fn_IPtoInt](  
  @ip   char(15)  
  )RETURNS   bigint  
  AS  
  BEGIN  
  DECLARE   @re   bigint  
  SET   @re=0  
  SELECT   @re=@re+LEFT(@ip,CHARINDEX('.',@ip+'.')-1)*ID  
  ,@ip=STUFF(@ip,1,CHARINDEX('.',@ip+'.'),'')  
  FROM(  
  SELECT   ID=CAST(16777216   as   bigint)  
  UNION   ALL   SELECT   65536  
  UNION   ALL   SELECT   256  
  UNION   ALL   SELECT   1)A  
  RETURN(@re)  
  END  
  GO  

--字符转数字
create function dbo.fn_IPCovertInt(@ip varchar(15))   
returns bigint   
begin   
    return parsename(@ip,4)*cast(16777216 as bigint)+parsename(@ip,3)*65536+parsename(@ip,2)*256+parsename(@ip,1)   
end 
GO


declare  @tb table (id int,sip varchar(15),eip varchar(15),areaname nvarchar(50),co nvarchar(50))
insert @tb select 1,'1.0.0.0','1.0.0.0','美国','亚太互联网络信息中心(CloudFlare节点)'
UNION ALL  select 2,'1.0.0.1','1.0.0.1','美国','APNIC&CloudFlare公共DNS服务器'
UNION ALL  select 3,'1.0.0.2','1.0.0.255','美国','亚太互联网络信息中心(CloudFlare节点)'
UNION ALL  select 4,'1.0.1.0','1.0.3.255','福建省','电信'
UNION ALL  select 5,'1.0.4.0','1.0.7.255','澳大利亚','墨尔本Goldenit有限公司'
UNION ALL  select 6,'1.0.8.0','1.0.15.255','广东省','电信'
UNION ALL  select 7,'1.0.16.0','1.0.31.255','日本','东京I2Ts'
UNION ALL  select 8,'1.0.32.0','1.0.63.255','广东省','电信'
UNION ALL  select 9,'1.0.64.0','1.0.127.255','日本','Energia通讯'
UNION ALL  select 10,'1.0.128.0','1.0.255.255','泰国','TOTNET'
UNION ALL  select 11,'1.1.0.0','1.1.0.257','福建省','电信'
--select *,dbo.fn_IP(sip) AS staIP,dbo.fn_IP(eip) AS endIP from @tb
select id,sip,eip,dbo.fn_IPCovertInt(sip) AS staIP,dbo.fn_IPCovertInt(eip) AS endIP,areaname,co from @tb
where dbo.fn_IPCovertInt(sip)<=dbo.fn_IPCovertInt('1.1.0.3') and  dbo.fn_IPCovertInt(eip)>=dbo.fn_IPCovertInt('1.1.0.3')
GO

declare  @tb table (id int,sip varchar(15),eip varchar(15),areaname nvarchar(50),co nvarchar(50))
insert @tb select 1,'1.0.0.0','1.0.0.0','美国','亚太互联网络信息中心(CloudFlare节点)'
UNION ALL  select 2,'1.0.0.1','1.0.0.1','美国','APNIC&CloudFlare公共DNS服务器'
UNION ALL  select 3,'1.0.0.2','1.0.0.255','美国','亚太互联网络信息中心(CloudFlare节点)'
UNION ALL  select 4,'1.0.1.0','1.0.3.255','福建省','电信'
UNION ALL  select 5,'1.0.4.0','1.0.7.255','澳大利亚','墨尔本Goldenit有限公司'
UNION ALL  select 6,'1.0.8.0','1.0.15.255','广东省','电信'
UNION ALL  select 7,'1.0.16.0','1.0.31.255','日本','东京I2Ts'
UNION ALL  select 8,'1.0.32.0','1.0.63.255','广东省','电信'
UNION ALL  select 9,'1.0.64.0','1.0.127.255','日本','Energia通讯'
UNION ALL  select 10,'1.0.128.0','1.0.255.255','泰国','TOTNET'
UNION ALL  select 11,'1.1.0.0','1.1.0.257','福建省','电信'
--select *,dbo.f_IP2Int(sip) AS staIP,dbo.f_IP2Int(eip) AS endIP from @tb
select id,sip,eip,dbo.[fn_IPtoInt](sip) AS staIP,dbo.[fn_IPtoInt](eip) AS endIP,areaname,co,dbo.[fn_IPtoInt]('1.1.0.3') AS NIP from @tb
where dbo.[fn_IPtoInt](sip)<=dbo.[fn_IPtoInt]('1.1.0.3') and  dbo.[fn_IPtoInt](eip)>=dbo.[fn_IPtoInt]('1.1.0.3')
GO


declare  @tb table (id int,sip varchar(15))
insert @tb select 1,'10.210.128.207'
UNION ALL  select 2,'10.210.128.206'
UNION ALL  select 3,'10.210.128.205'
UNION ALL  select 4,'10.210.128.204'
UNION ALL  select 5,'10.210.128.203'
UNION ALL  select 6,'10.210.128.202'
UNION ALL  select 7,'10.210.128.201'
select id,sip,dbo.fn_IPCovertInt(sip) AS IPINT from @tb
where dbo.fn_IPCovertInt(sip) between  dbo.fn_IPCovertInt('10.210.128.203') and dbo.fn_IPCovertInt('10.210.128.205')
GO

 csharp:

  /// <summary>
        /// 将IPv4格式的字符串转换为int型表示
        /// </summary>
        /// <param name="strIPAddress">IPv4格式的字符</param>
        /// <returns></returns>
        public static int IPToNumber(string strIPAddress)
        {
            //将目标IP地址字符串strIPAddress转换为数字
            string[] arrayIP = strIPAddress.Split('.');
            int sip1 = Int32.Parse(arrayIP[0]);
            int sip2 = Int32.Parse(arrayIP[1]);
            int sip3 = Int32.Parse(arrayIP[2]);
            int sip4 = Int32.Parse(arrayIP[3]);
            int tmpIpNumber;
            tmpIpNumber = sip1 * 256 * 256 * 256 + sip2 * 256 * 256 + sip3 * 256 + sip4;
            return tmpIpNumber;
        }


        /// <summary>
        /// 将int型表示的IP还原成正常IPv4格式。
        /// </summary>
        /// <param name="intIPAddress">int型表示的IP</param>
        /// <returns></returns>
        public static string NumberToIP(int intIPAddress)
        {
            int tempIPAddress;
            //将目标整形数字intIPAddress转换为IP地址字符串
            //-1062731518 192.168.1.2 
            //-1062731517 192.168.1.3 
            if (intIPAddress >= 0)
            {
                tempIPAddress = intIPAddress;
            }
            else
            {
                tempIPAddress = intIPAddress + 1;
            }
            int s1 = tempIPAddress / 256 / 256 / 256;
            int s21 = s1 * 256 * 256 * 256;
            int s2 = (tempIPAddress - s21) / 256 / 256;
            int s31 = s2 * 256 * 256 + s21;
            int s3 = (tempIPAddress - s31) / 256;
            int s4 = tempIPAddress - s3 * 256 - s31;
            if (intIPAddress < 0)
            {
                s1 = 255 + s1;
                s2 = 255 + s2;
                s3 = 255 + s3;
                s4 = 255 + s4;
            }
            string strIPAddress = s1.ToString() + "." + s2.ToString() + "." + s3.ToString() + "." + s4.ToString();
            return strIPAddress;
        }

        /// <summary>
        /// IP转数字
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static long IpToInt(string ip)
        {
            char[] separator = new char[] { '.' };
            string[] items = ip.Split(separator);
            return long.Parse(items[0]) << 24
                    | long.Parse(items[1]) << 16
                    | long.Parse(items[2]) << 8
                    | long.Parse(items[3]);
        }
        /// <summary>
        /// 数字转IP
        /// </summary>
        /// <param name="ipInt"></param>
        /// <returns></returns>
        public static string IntToIp(long ipInt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append((ipInt >> 24) & 0xFF).Append(".");
            sb.Append((ipInt >> 16) & 0xFF).Append(".");
            sb.Append((ipInt >> 8) & 0xFF).Append(".");
            sb.Append(ipInt & 0xFF);
            return sb.ToString();
        }

     /// <summary>
        ///从文本导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            if (backgroundWorker1.IsBusy)
                return;




            //string[] lines = System.IO.File.ReadAllLines(@"IP.txt",Encoding.Default);
            //foreach (string line in lines)
            //{
            //    // Use a tab to indent each line of the file.
            //    Console.WriteLine("\t" + line);
            //    string[] tempstr = line.Split('\t');
            //}


            //2
            //标示列数   
            err = 0;
            int columnCount = 0;
            DataTable dt = new DataTable();
            dt.Columns.Add("startIP", typeof(string));
            dt.Columns.Add("endIP", typeof(string));
            dt.Columns.Add("区域", typeof(string));
            dt.Columns.Add("服务商", typeof(string));

            string strLine = "";
            //記錄每行記錄中的各字段内容
            string[] aryLine;
            //标示列数      
            FileStream fs = new FileStream(@"ip.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read);
            StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
            QQwryIP inf = null;
            //逐行读取txt中的数據
            while ((strLine = sr.ReadLine()) != null)
            {
                inf = new QQwryIP();
                aryLine = strLine.Split('\t');//tab分隔符
                aryLine = Regex.Split(strLine, "\\s+", RegexOptions.IgnoreCase);  //以多个空格
                columnCount = aryLine.Count();
                if (aryLine.Count() > 2)
                {
                    inf.IPStart = aryLine[0];
                    inf.IPStartInt = IPToNumber(aryLine[0]);  //536782	IP数据库共有数据	:	528129	条  //删除最后这一边统计的数据
                    inf.IPend = aryLine[1];
                    inf.IPendInt = IPToNumber(aryLine[1]);
                    if (columnCount > 2)
                        inf.AreaName = aryLine[2];
                    else
                        inf.AreaName = "";
                    if (columnCount > 3)
                    {
                        if (aryLine[3] == "dusystem.com")
                            inf.CompanyName = "geovindu:未知服务提供商";
                        else
                            inf.CompanyName = aryLine[3];
                    }
                    else
                        inf.CompanyName = "";
                    // bll.Add(inf);                  
                    lists.Add(inf);
                    err++;
                }

                //DataRow dr = dt.NewRow();
               
                //for (int j = 0; j < columnCount; j++)
                //{
                //    dr[j] = aryLine[j].ToUpper();

                //}
                //dt.Rows.Add(dr);
            }
            sr.Close();
            fs.Close();
            //
            this.label2.Text = lists.Count.ToString();
            this.progressBar1.Maximum = 100;
            backgroundWorker1.RunWorkerAsync("hello");
            //Thread t2 = new Thread(Add);
            //Thread.Sleep(500);
            //t2.Start(lists);  
            // 传入参数
            //2
            //mManualEvent = new ManualResetEvent(false); // 实例
           // ThreadPool.QueueUserWorkItem(Add, lists);
            //Thread.Sleep(100); // 等待
           // mManualEvent.Set();  // 发出信号,让线程继续执行
            //WaitHandle.WaitAll(mManualEvent); 

            this.Cursor = Cursors.Default;
           // MessageBox.Show(err.ToString());

           // this.dataGridView1.DataSource = dt;
        }

  

 

  

 

posted @ 2015-06-24 17:04  ®Geovin Du Dream Park™  阅读(2009)  评论(2编辑  收藏  举报