how to validate IP address in c# and javascript?

Posted by Allemahesh under C# on 7/18/2013 | Points: 10 | Views : 1483 | Status : [Member] [MVP] | Replies : 5
how to validate IP address in c# and javascript.




Responses

Posted by: Ssj_Kumar on: 7/18/2013 [Member] Starter | Points: 25

Up
0
Down
string strIPAddress= "192.0.0.1";
IPAddress Address;

if(IPAddress.TryParse(strIPAddress, out Address))
{
//Valid IP Address
}

Regards,
Jayakumar Selvakani

Allemahesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Allemahesh on: 7/18/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
Dear Kumar,
I have tried your code, but not working.
E.g.:
string strIPAddress = "244";
IPAddress Address;
if (IPAddress.TryParse(strIPAddress, out Address))
{
//Valid IP Address
}

This code is giving true but it should be false.
Can you help me.



Allemahesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ssj_Kumar on: 7/18/2013 [Member] Starter | Points: 25

Up
0
Down
If you give 244 it will assume like 0.0.0.244

Use the below code

string strIPAddress = "192.0.0.244";
IPAddress Address;
string[] strAddress = strIPAddress.Split('.');
if (strAddress.Count() == 4)
{
if (IPAddress.TryParse(strIPAddress, out Address))
{
//Valid IP Address
}
}
else
{
//please provide valid IP address
}

Regards,
Jayakumar Selvakani

Allemahesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Allemahesh on: 7/22/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
I understand, but if user pass 244 as an ip, then it is invalid. But your code is showing a valid one. So how to do this?

Allemahesh, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ssj_Kumar on: 7/22/2013 [Member] Starter | Points: 25

Up
0
Down
did you tried with the second code? bcz it will solve that problem

Regards,
Jayakumar Selvakani

Allemahesh, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response