c# - 如何在客户端(使用 javascript)和服务器端(使用 c#)验证 mac 地址和 ip 地址

标签 c# .net asp.net javascript asp.net-mvc

我的团队使用 Asp.net MVC(c#) 做一个与网络相关的项目。

我需要在客户端(使用 javascript)和服务器端(使用 c#)验证 ma​​c 地址和 ipaddress 以进行简单的表单输入。我没有得到验证 mac 地址和 ip 地址的好解决方案。

我在谷歌上搜索了一个很好的用户界面来验证 mac 地址,方法是在两个数字后加上冒号,例如:“XX:XX:XX:XX:XX:XX”,使用掩码输入。请提供引用/指导来实现这个.任何用于实现屏蔽输入的 jquery 插件。

最佳答案

如果您需要获取服务器端的地址(ip、ma​​c),下面的代码将帮助您:

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/

相关文章:

c# - 如何在 .NET WinForm 应用程序中显示 React App?

asp.net - 如何使用 MVC Razor 生成 SVG

c# - 410 状态显示 "The page you requested was removed"

c# - ZXing.Net二维码大小

c# - 我在字符串末尾得到空字符

c# - 我遇到以下错误 System.Data.SqlClient.SqlException : in C#

c# - 使用 C# 在 Powerpoint 2013 中创建具有多个系列的图表

c# - 为什么 SQL 查询不运行?

c# - Microsoft.Win32.SaveFileDialog 有效文件名问题

asp.net - 在 ie6 中测试有哪些好的解决方案?