How to Validate mac address & ipaddress in client side(using javascript) & server side(using c#)
My team doing a project related to network using Asp.net MVC(c#).
I need to validate mac address & ipaddress in client side(using javascript) & server side(using c#) for a simple form entry. I didn't get a good solution for validating mac address & ip addresss.
I searched google for finding a good user interface for validating mac address by giving colon after two number eg: "XX:XX:XX:XX:XX:XX" by using Masked Input.Please give reference/guidance for imp开发者_StackOverflow中文版lementing this. Any jquery plugin for implementing Masked Input.
If you need to get the addresses (ip,mac) server side the code below will help you:
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);
}
}
are you tring to validate the format or the actual addresses?
if the former, try regualar expressions...
IP Address: \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
Or take a look here regarding Mac Addresses
精彩评论