c# 生成連續MAC地址

class Program
    {
        public static void Main(String[] args)
        {
            String filePath = "f://mac.txt";

            genPatchMAC("00:00:00:00:00:00", 100, filePath);
            Console.WriteLine("finished!");
        }
        public static String pattern = "[0-9a-fA-F]{12}";
        //public static String patternSn = "[0-9A-Z]{18}";
        public static void genPatchMAC(String initialMAC, int count, String filePath)
        {
            String startMAC = initialMAC.Replace(":", "");
            bool isMatch = Regex.IsMatch(startMAC,pattern);
            if (isMatch == false)
            { 
                Console.WriteLine(startMAC + "初始MAC地址非法");
                Environment.Exit(0);
            }
            try
            {
                using (StreamWriter write = new StreamWriter(new FileStream(filePath,FileMode.Append)))
                {
                    BigInteger remoteMAC = BigInteger.Parse(startMAC, System.Globalization.NumberStyles.HexNumber);
                    BigInteger increase = new BigInteger(1);
                    String resultMAC = "";
                    for (int i = 0; i < count; i++)
                    {
                        resultMAC = remoteMAC.ToString("X");
                        write.Write(formatMAC(resultMAC) + "\r\n");

                        remoteMAC = BigInteger.Add(remoteMAC, increase);
                    }
                    write.Close();
                }
            }
            catch (IOException e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }

        private static String formatMAC(String str)
        {
            StringBuilder temMAC = new StringBuilder("");
            for (int i = 1; i <= 12; i++)
            {
                temMAC.Append(str[i - 1]);
                if (i % 2 == 0)
                {
                    temMAC.Append(":");
                }
            }
            String MAC = temMAC.ToString().Substring(0, 17);
            return MAC;
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章