Feedback

C# - Convert MAC string to byte array

Veröffentlicht von am 5/4/2008
(2 Bewertungen)
Diese Methode konvertiert einen string wo eine MAC Adresse steht zu einem byte array.
Mögliche Inputs wären:
AA:BB:CC:DD:EE:FF
AA-BB-CC-DD-EE-FF
AABB.CCDD.EEFF ( Cisco Notation )
AABBCCDDEEFF

bei ungültigen inputs werden exceptions geworfen.( siehe comment )
        /// <summary>
        /// Converts an mac string to an byte array
        /// </summary>
        /// <param name="mac">The physical MAC address to convert. The string can have on of the fallowing formats.
        /// <list type="bullet">
        /// <item>
        /// <description>AA:BB:CC:DD:EE:FF</description>
        /// </item>
        /// <item>
        /// <description>AA-BB-CC-DD-EE-FF</description>
        /// </item>
        /// <item>
        /// <description>AABB.CCDD.EEFF</description>
        /// </item>
        /// <item>
        /// <description>AABBCCDDEEFF</description>
        /// </item>
        /// </list>
        /// </param>
        /// <exception cref="ArgumentNullException">thrown if <paramref name="mac"/> is null </exception>
        /// <exception cref="ArgumentException">thrown if <paramref name="mac"/> is not valid</exception>
        public static byte[] GetMacArray(string mac)
        {
            if (string.IsNullOrEmpty(mac)) throw new ArgumentNullException("mac");
            byte[] ret = new byte[6];
            try
            {
                string[] tmp = mac.Split(':', '-');
                if (tmp.Length != 6)
                {
                    tmp = mac.Split('.');
                    if (tmp.Length == 3)
                    {
                        for (int i = 0; i < 3; i++)
                        {
                            ret[i * 2] = byte.Parse(tmp[i].Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
                            ret[i * 2 + 1] = byte.Parse(tmp[i].Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
                        }
                    }
                    else
                        for (int i = 0; i < 12; i+=2)
                            ret[i/2] = byte.Parse(mac.Substring(i,2), System.Globalization.NumberStyles.HexNumber);
                }
                else
                    for (int i = 0; i < 6; i++)
                        ret[i] = byte.Parse(tmp[i], System.Globalization.NumberStyles.HexNumber);
            }
            catch
            {
                throw new ArgumentException("Argument doesn't have the correct format: " + mac, "mac");
            }
            return ret;
        }
Abgelegt unter MAC, string, byte array.

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!