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


            /// <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}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])";
                if (System.Text.RegularExpressions.Regex.IsMatch(ip, pattrn))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
  • 相关阅读:
    MySQL数据库初识
    Python中面向对象初识到进阶
    python 函数进阶
    Python 函数的初识
    Python的发展与应用
    什么是产品经理 以及职责
    I/O----复制文本文件
    获取次日日期(主要两种方法)
    vector以及array和数组
    编辑软件注释快捷键
  • 原文地址:https://www.cnblogs.com/wangboke/p/6112226.html
Copyright © 2020-2023  润新知