您如何验证字符串是C中的有效MAC地址? [英] How do you validate that a string is a valid MAC address in C?

查看:469
本文介绍了您如何验证字符串是C中的有效MAC地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:


12:45:ff:ab:aa:cd    is valid
45:jj:jj:kk:ui>cd    is not valid

推荐答案

以下代码检查有效的MAC地址(带或不带:"分隔符):

The following code checks for valid MAC addresses (with or w/o the ":" separator):

#include <ctype.h>

int isValidMacAddress(const char* mac) {
    int i = 0;
    int s = 0;

    while (*mac) {
       if (isxdigit(*mac)) {
          i++;
       }
       else if (*mac == ':' || *mac == '-') {

          if (i == 0 || i / 2 - 1 != s)
            break;

          ++s;
       }
       else {
           s = -1;
       }


       ++mac;
    }

    return (i == 12 && (s == 5 || s == 0));
}

代码检查以下内容:

  • 输入字符串mac恰好包含12个十六进制数字.
  • 如果输入字符串中出现分隔冒号:,则仅在偶数个十六进制数字之后出现.
  • that the input string mac contains exactly 12 hexadecimal digits.
  • that, if a separator colon : appears in the input string, it only appears after an even number of hex digits.

它是这样的:

  • i,它是mac中的十六进制数字,被初始化为0.
  • while循环输入字符串中的每个字符,直到字符串结尾或检测到12个十六进制数字.
    • 如果当前字符(*mac)是有效的十六进制数字,则i递增,然后循环检查下一个字符.
    • 否则,循环将检查当前字符是否为分隔符(冒号或破折号);如果是这样,它将验证每对十六进制数字是否有一个分隔符.否则,循环将中止.
    • i,which is the number of hex digits in mac, is initialized to 0.
    • The while loops over every character in the input string until either the string ends, or 12 hex digits have been detected.
      • If the current character (*mac) is a valid hex digit, then i is incremented, and the loop examines the next character.
      • Otherwise, the loop checks if the current character is a separator (colon or a dash); if so, it verifies that there is one separator for every pair of hex digits. Otherwise, the loop is aborted.

      如果您不想接受分隔符,只需将return语句更改为:

      If you don't want to accept separators, simply change the return statement to:

      return (i == 12 && s == 0);
      

      这篇关于您如何验证字符串是C中的有效MAC地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆