如何验证 C 中的字符串是否为有效的 MAC 地址?
例子:
12:45:ff:ab:aa:cd is valid 45:jj:jj:kk:ui>cd is not valid
example:
12:45:ff:ab:aa:cd is valid 45:jj:jj:kk:ui>cd is not valid
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下代码检查有效的 MAC 地址(带或不带“:”分隔符):
该代码检查以下内容:
mac
是否恰好包含 12 个十六进制数字。:
出现在输入字符串中,则它仅出现在偶数个十六进制数字之后。它的工作原理如下:
i
,它是mac
中的十六进制数字的数量,被初始化为0。while
循环遍历mac
中的每个字符。输入字符串,直到字符串结束或检测到 12 个十六进制数字。*mac
) 是有效的十六进制数字,则i
递增,并且循环检查下一个字符。如果您不想接受分隔符,只需将 return 语句更改为:
The following code checks for valid MAC addresses (with or w/o the ":" separator):
The code checks the following:
mac
contains exactly 12 hexadecimal digits.:
appears in the input string, it only appears after an even number of hex digits.It works like this:
i
,which is the number of hex digits inmac
, is initialized to 0.while
loops over every character in the input string until either the string ends, or 12 hex digits have been detected.*mac
) is a valid hex digit, theni
is incremented, and the loop examines the next character.If you don't want to accept separators, simply change the return statement to:
我需要验证和解析 ANSI C 中的 MAC 地址,所以这是函数。如果 MAC 地址已通过验证,它将返回 1(它将接受 12 个十六进制字符,小写或大写,带或不带冒号,包括部分正确的输入,如
b3:0a:23:48fad3
) 。它在 Cortex m3 控制器上的嵌入式应用程序中为我完成了这项工作。该函数还将接受来自网页的直接输入(这实际上就是我使用它的方式),因此它将接受冒号作为
%3A
字符。结果是一个六字节数组。对于此,您必须
#include
。输入字符串 (
*mac
) 必须以零结尾才能使函数正常工作。I needed to both validate and parse MAC address in ANSI C, so here's the function. It returns 1 in case the mac address has been validated (it will accept 12 hex characters, lower case or upper case, with or without colons, including partially correct input like
b3:0a:23:48fad3
). It does the job for me in an embedded application on a cortex m3 controller.The function will also accept direct input from a web page (that's actually how i use it), and therefore it will accept colons as
%3A
characters.The result is a six byte array. You will have to
#include <cctype>
for this one.The input string (
*mac
) must be zero-terminated for the function to work.这是另一个检查 MAC 地址完整性的简单函数
Here is another simple function to check sanity of MAC address
您可以依靠 sscanf 检查所提供的 MAC 地址的格式和内容,例如
You can rely on the sscanf to check the format and content of the provided MAC address, something like