码迷,mamicode.com
首页 > Windows程序 > 详细

C# 获取本机IP地址以及转换字符串

时间:2016-11-29 09:37:37      阅读:540      评论:0      收藏:0      [点我收藏+]

标签:获取本机ip   ons   etl   ext   tostring   ipaddress   param   ip地址   style   

        /// <summary>
        /// IP地址转化
        /// </summary>
        /// <param name="ipaddr">整型的IP地址</param>
        /// <returns>字符串的IP地址</returns>
        private string UintIPToStringIP(uint ipaddr)
        {
            string hexStr = ipaddr.ToString("X8");
            int ip1 = Convert.ToInt32(hexStr.Substring(0, 2), 16);
            int ip2 = Convert.ToInt32(hexStr.Substring(2, 2), 16);
            int ip3 = Convert.ToInt32(hexStr.Substring(4, 2), 16);
            int ip4 = Convert.ToInt32(hexStr.Substring(6, 2), 16);
            return ip4 + "." + ip3 + "." + ip2 + "." + ip1;
        }

        /// <summary>
        /// IP地址转化
        /// </summary>
        /// <param name="ipaddr">字符串的IP地址</param>
        /// <returns>整型的IP地址</returns>
        private uint StringIPToUintIP(string ipaddr)
        {
            string[] ips = ipaddr.Split(.);
            return Convert.ToUInt32(ips[3]) * 256 * 256 * 256 + Convert.ToUInt32(ips[2]) * 256 * 256 + Convert.ToUInt32(ips[1]) * 256 + Convert.ToUInt32(ips[0]);          
        }

        /// <summary>
        /// 获取本机IP地址
        /// </summary>
        /// <returns></returns>
        private string GetLocalIPAddress()
        {
            string resultIP = string.Empty;
            System.Net.IPAddress[] ips = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList;
            foreach (System.Net.IPAddress ip in ips)
            {
                if (IsCorrentIP(ip.ToString()))
                {
                    resultIP = ip.ToString();
                    break;
                }
            }
            return resultIP;
        }

        /// <summary>
        /// 验证IP地址是否有效
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        private bool IsCorrentIP(string ip)
        {
            string pattrn = @"(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])";
            if (System.Text.RegularExpressions.Regex.IsMatch(ip, pattrn))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

 

C# 获取本机IP地址以及转换字符串

标签:获取本机ip   ons   etl   ext   tostring   ipaddress   param   ip地址   style   

原文地址:http://www.cnblogs.com/wangboke/p/6112226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!