我的团队使用 Asp.net MVC(c#) 做一个与网络相关的项目。
我需要在客户端(使用 javascript)和服务器端(使用 c#)验证 mac 地址和 ipaddress 以进行简单的表单输入。我没有得到验证 mac 地址和 ip 地址的好解决方案。
我在谷歌上搜索了一个很好的用户界面来验证 mac 地址,方法是在两个数字后加上冒号,例如:“XX:XX:XX:XX:XX:XX”,使用掩码输入。请提供引用/指导来实现这个.任何用于实现屏蔽输入的 jquery 插件。
最佳答案
如果您需要获取服务器端的地址(ip、mac),下面的代码将帮助您:
public partial class RemoteClientInfo : System.Web.UI.Page
{
public class NetUtils
{
//http://msdn.microsoft.com/en-us/library/aa366358(VS.85).aspx
[System.Runtime.InteropServices.DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);
private static System.Net.IPAddress GetIpAddress(string address)
{
System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(address);
if (hostEntry != null)
{
foreach (System.Net.IPAddress ipAddress in hostEntry.AddressList)
{
if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return ipAddress;
}
}
}
return null;
}
public static string GetMacAddress(string address)
{
System.Net.IPAddress ipAddress = GetIpAddress(address);
if (ipAddress != null)
{
byte[] addressBytes = ipAddress.GetAddressBytes();
byte[] macAddress = new byte[6];
uint macAddressLen = (uint)macAddress.Length;
if (SendARP(BitConverter.ToInt32(addressBytes, 0), 0, macAddress, ref macAddressLen) == 0)
{
return BitConverter.ToString(macAddress);
}
}
return null;
}
}
protected void GetClientInfoButton_Click(object sender, EventArgs e)
{
string remoteIp = System.Web.HttpContext.Current.Request.UserHostAddress;
string remoteMacAddr = NetUtils.GetMacAddress(remoteIp);
this.InfoTextBox.Text = string.Format("ip=[{0}] mac=[{1}]", remoteIp, remoteMacAddr);
}
}
关于c# - 如何在客户端(使用 javascript)和服务器端(使用 c#)验证 mac 地址和 ip 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2973222/