2010-06-04 108 views
7

我的團隊正在使用Asp.net MVC(c#)做一個與網絡相關的項目。如何在客戶端(使用javascript)和服務器端(使用c#)驗證mac地址和ip地址

我需要在客戶端側,用於一個簡單的表格條目來驗證MAC地址& IPADDRESS(使用javascript)&服務器側(使用C#)。我沒有得到一個很好的解決方案來驗證mac地址& ip地址。

我搜索谷歌找到一個良好的用戶界面驗證mac地址,通過使用掩碼輸入給兩個數字後例如:「XX:XX:XX:XX:XX:XX」冒號。請給參考/指導實施這個。任何用於實現Masked Input的jquery插件。

回答

0

您是否正在驗證格式或實際地址?

如果是前者,儘量regualar表情...

IP地址: \ B(25 [0-5] | 2 [0-4] [0-9] | [01] [0? -9] [0-9])(25 [0-5] | 2 [0-4] [0-9] | [01] [0-9] [0-9])(25?。 [0-5] | 2 [0-4] [0-9] | [01] [0-9] [0-9])(25 [0-5] |?2 [0-4] [ 0-9] |?[01] [0-9] [0-9])\ b

或者採取措施的Mac看看here地址

+0

我需要驗證格式和實際地址 – amexn 2010-06-04 10:39:53

+0

使用正則表達式來驗證格式使用正則表達式(無論是客戶端或服務器 - 可能是最好的兩個)然後使用服務器通過ping測試連接到IP地址(http ://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx)和http://mycomponent.blogspot.com/2009/05/get-mac-address-in-c-如果有問題的MAC涉及IP,則從-ip.html – justcompile 2010-06-04 10:49:07

2

如果您需要獲得地址(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); 
     } 
}