Value out of range exception when setting a string member of INetFwRule - c#

I'm trying to add a firewall rule for TCP Port 1433, with a specific group using the NetFwTypeLib library.
But adding the port into the LocalPorts variable as integer converted into a string or just as a simple "1433" string, returns a Value out of range exception.
Removing the port and just using all ports works fine.
Here is the code I used:
bool CreateRule(string sName, string sPort, NET_FW_IP_PROTOCOL_ ProtocolType, string sIpAdress, string sGroup = "")
{
try
{
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
firewallRule.Description = "Used to allow Server access.";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
firewallRule.Enabled = true;
firewallRule.Name = sName;
firewallRule.Grouping = sGroup;
firewallRule.LocalPorts = sPort; // "1433" causes out of range exception
firewallRule.RemoteAddresses = sIpAdress;
firewallRule.Protocol = (int)ProtocolType;
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(firewallRule);
return true;
}
catch
{
return false;
}
}
Setting the firewallRule.LocalPorts member causes the exception.
Does someone have an idea what's going wrong?

You have to put the Protocol type before the Port, so it is valid.

Related

Discover all devices on LAN

In my Xamarin Forms application, I am trying to discover all devices on the local network that I am connected to. My approach is to first get the device IP address, and use to first 3 numbers to know what the gateway is (first number is always 192). And then, ping every address on that gateway. Here is my code:
public partial class MainPage : ContentPage
{
private List<Device> discoveredDevices = new List<Device>();
public MainPage()
{
InitializeComponent();
Ping_all();
}
private string GetCurrentIp()
{
IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
string ipAddress = string.Empty;
if (addresses != null && addresses[0] != null)
{
ipAddress = addresses[0].ToString();
}
else
{
ipAddress = null;
}
return ipAddress;
}
public void Ping_all()
{
string ip = GetCurrentIp();
if (ip != null)
{
//Extracting and pinging all other ip's.
string[] array = ip.Split('.');
string gateway = array[0] + "." + array[1] + "." + array[2];
for (int i = 2; i <= 255; i++)
{
string ping_var = $"{gateway}.{i}";
//time in milliseconds
Ping(ping_var, 4, 4000);
}
}
}
public void Ping(string host, int attempts, int timeout)
{
for (int i = 0; i < attempts; i++)
{
new Thread(delegate ()
{
try
{
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
ping.PingCompleted += new PingCompletedEventHandler(PingCompleted);
ping.SendAsync(host, timeout, host);
// PingCompleted never gets called
}
catch(Exception e)
{
// Do nothing and let it try again until the attempts are exausted.
// Exceptions are thrown for normal ping failurs like address lookup
// failed. For this reason we are supressing errors.
}
}).Start();
}
}
private void PingCompleted(object sender, PingCompletedEventArgs e)
{
string ip = (string)e.UserState;
if (e.Reply != null && e.Reply.Status == IPStatus.Success)
{
string hostname = GetHostName(ip);
string macaddres = GetMacAddress(ip);
var device = new Device()
{
Hostname = hostname,
IpAddress = ip,
MacAddress = macaddres
};
discoveredDevices.Add(device);
}
}
public string GetHostName(string ipAddress)
{
try
{
IPHostEntry entry = Dns.GetHostEntry(ipAddress);
if (entry != null)
{
return entry.HostName;
}
}
catch (SocketException)
{
}
return null;
}
public string GetMacAddress(string ipAddress)
{
string macAddress = string.Empty;
System.Diagnostics.Process Process = new System.Diagnostics.Process();
Process.StartInfo.FileName = "arp";
Process.StartInfo.Arguments = "-a " + ipAddress;
Process.StartInfo.UseShellExecute = false;
Process.StartInfo.RedirectStandardOutput = true;
Process.StartInfo.CreateNoWindow = true;
Process.Start();
string strOutput = Process.StandardOutput.ReadToEnd();
string[] substrings = strOutput.Split('-');
if (substrings.Length >= 8)
{
macAddress = substrings[3].Substring(Math.Max(0, substrings[3].Length - 2))
+ "-" + substrings[4] + "-" + substrings[5] + "-" + substrings[6]
+ "-" + substrings[7] + "-"
+ substrings[8].Substring(0, 2);
return macAddress;
}
else
{
return "OWN Machine";
}
}
}
I get to the part where I try to ping:
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
ping.PingCompleted += new PingCompletedEventHandler(PingCompleted);
ping.SendAsync(host, timeout, host);
But PingCompleted never gets called. No exception is thrown either. Any idea why? I'm running this on a physical Android device.
EDIT
PingCompleted started getting called for me now, not sure why it wasn't working before. But it now crashes in my GetMacAddress function on the line Process.Start(); because it can not find the resource.
I ended up using this really robust and easy to use library:
https://github.com/Yortw/RSSDP
It doesn't actually find all devices on the network, instead it uses SSDP (Simple Search Discovery Protocol) to quickly find all devices that are broadcasting a service with this protocol on the network. I filtered it to only scan devices running my app, which is what I actually needed. It takes only a second to discover my devices, which is much faster than pinging 255 addresses.
In the documentation you will see:
var deviceDefinition = new SsdpRootDevice()
{
CacheLifetime = TimeSpan.FromMinutes(30), //How long SSDP clients can cache this info.
Location = new Uri("http://mydevice/descriptiondocument.xml"), // Must point to the URL that serves your devices UPnP description document.
DeviceTypeNamespace = "my-namespace",
DeviceType = "MyCustomDevice",
FriendlyName = "Custom Device 1",
Manufacturer = "Me",
ModelName = "MyCustomDevice",
Uuid = GetPersistentUuid() // This must be a globally unique value that survives reboots etc. Get from storage or embedded hardware etc.
};
For the Location I set it as my device's IP. So that another device that discovers it can have the IP too. I don't think it's meant to be used this way, but it worked for me and I don't see why not.
I tested it on 2 physical Android devices.

a list of all users: Ldap referral error (LDAPReferralException)

I am using active directory and want a list of all users, basically in dotnet core. But I am receiving an exception:
Search result reference received, and referral following is off
Below is my code.
LdapSearchResults lsc = lc.Search("DC = xyz, DC = local", LdapConnection.SCOPE_ONE , "(|(objectClass = person)(objectClass = user))", null, false);
Necromancing - just in case the links go dark.
To fix it in your application, set ReferralFollowing to true.
if you get the message
Search result reference received, and referral following is off
, add
Novell.Directory.Ldap.LdapSearchConstraints cons = lc.SearchConstraints;
cons.ReferralFollowing = true;
lc.Constraints = cons;
to your code.
Example:
public static void GetUsers()
{
System.Collections.Generic.List<ARSoft.Tools.Net.Dns.SrvRecord> lsLdap = GetLdap();
ARSoft.Tools.Net.Dns.SrvRecord ldap = lsLdap[0];
string[] attrs = new string[] { "cn", "distinguishedName", "sAMAccountName", "userPrincipalName", "displayName", "givenName", "sn", "mail", "mailNickname", "memberOf", "homeDirectory", "msExchUserCulture" };
// CN = Common Name
// OU = Organizational Unit
// DC = Domain Component
string searchBase = "DC=cor,DC=local";
string searchFilter = "(&(objectClass=user)(objectCategory=person))";
string ldapHost = MySamples.TestSettings.ldapHost;
int ldapPort = MySamples.TestSettings.ldapPort;//System.Convert.ToInt32(args[1]);
string loginDN = MySamples.TestSettings.loginDN; // args[2];
string password = MySamples.TestSettings.password; // args[3];
Novell.Directory.Ldap.LdapConnection lc = new Novell.Directory.Ldap.LdapConnection();
int ldapVersion = Novell.Directory.Ldap.LdapConnection.Ldap_V3;
try
{
// connect to the server
lc.Connect(ldap.Target.ToString(), ldap.Port);
// bind to the server
lc.Bind(ldapVersion, loginDN, password);
Novell.Directory.Ldap.LdapSearchConstraints cons = lc.SearchConstraints;
cons.ReferralFollowing = true;
lc.Constraints = cons;
// To enable referral following, use LDAPConstraints.setReferralFollowing passing TRUE to enable referrals, or FALSE(default) to disable referrals.
Novell.Directory.Ldap.LdapSearchResults lsc = lc.Search(searchBase,
Novell.Directory.Ldap.LdapConnection.SCOPE_SUB,
searchFilter,
attrs,
false,
(Novell.Directory.Ldap.LdapSearchConstraints)null);
while (lsc.HasMore())
{
Novell.Directory.Ldap.LdapEntry nextEntry = null;
try
{
nextEntry = lsc.Next();
}
catch (Novell.Directory.Ldap.LdapReferralException eR)
{
// https://stackoverflow.com/questions/46052873/ldap-referal-error
// The response you received means that the directory you are requesting does not contain the data you look for,
// but they are in another directory, and in the response there is the information about the "referral" directory
// on which you need to rebind to "redo" the search.This principle in LDAP are the referral.
// https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/bp31k5d.html
// To enable referral following, use LDAPConstraints.setReferralFollowing passing TRUE to enable referrals, or FALSE (default) to disable referrals.
// are you sure your bind user meaning
// auth.impl.ldap.userid=CN=DotCMSUser,OU=Service Accounts,DC=mycompany,DC=intranet
// auth.impl.ldap.password = mypassword123
// has permissions to the user that is logging in and its groups?
System.Diagnostics.Debug.WriteLine(eR.LdapErrorMessage);
}
catch (Novell.Directory.Ldap.LdapException e)
{
// WARNING: Here catches only LDAP-Exception, no other types...
System.Console.WriteLine("Error: " + e.LdapErrorMessage);
// Exception is thrown, go for next entry
continue;
}
var atCN = nextEntry.getAttribute("cn");
var atUN = nextEntry.getAttribute("sAMAccountName");
var atDN = nextEntry.getAttribute("distinguishedName");
var atDIN = nextEntry.getAttribute("displayName");
if (atCN != null)
System.Console.WriteLine(atCN.StringValue);
if (atUN != null)
System.Console.WriteLine(atUN.StringValue);
if (atDN != null)
System.Console.WriteLine(atDN.StringValue);
if (atDIN != null)
System.Console.WriteLine(atDIN.StringValue);
System.Console.WriteLine("\n" + nextEntry.DN);
Novell.Directory.Ldap.LdapAttributeSet attributeSet = nextEntry.getAttributeSet();
System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
while (ienum.MoveNext())
{
Novell.Directory.Ldap.LdapAttribute attribute = (Novell.Directory.Ldap.LdapAttribute)ienum.Current;
string attributeName = attribute.Name;
string attributeVal = attribute.StringValue;
System.Console.WriteLine(attributeName + "value:" + attributeVal);
}
}
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
}
finally
{
// disconnect with the server
lc.Disconnect();
}
}
You have to activate the behaviour which will follow the referral returned by the directory.
The response you received means that the directory you are requesting does not contain the data you look for, but they are in another directory, and in the response there is the information about the "referral" directory on which you need to rebind to "redo" the search. This principle in LDAP are the referral.
I don't know how to do it in C#, but maybe have a look at :
https://www.novell.com/documentation/developer/ldapcsharp/?page=/documentation/developer/ldapcsharp/cnet/data/bp31k5d.html

Check Valid email address in c#

I'm sending email using smtp services in my c# windows application. I have to perform in a best way to reduce the email bounce rate. I have to check the provided email address is valid or not. I'm using the code.
private void btnCheckValid_Click(object sender, EventArgs e)
{
if (isRealDomain(textBox1.Text.Trim()) == true)
MessageBox.Show("Valid Email Address!");
}
private bool isRealDomain(string inputEmail)
{
bool isReal = false;
try
{
string[] host = (inputEmail.Split('#'));
string hostname = host[1];
IPHostEntry IPhst = Dns.GetHostEntry(hostname);
IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0], 25);
Socket s = new Socket(endPt.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
s.Connect(endPt);
s.Close();
isReal = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
isReal = false;
}
return isReal;
}
By checking the real domain I can identified the Hosted IP but the email address is created on the host or not.
with regex (regular expression ) I can valid only format.
So my question is how to find only valid address of any domain in c#.
You can import System.ComponentModel.DataAnnotations and use it in this way:
private bool validMail(string address)
{
EmailAddressAttribute e = new EmailAddressAttribute();
if (e.IsValid(address))
return true;
else
return false;
}
You can use regular expressions like:
public static bool IsValidEmailAddress(string emailaddress)
{
try
{
Regex rx = new Regex(
#"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*#[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
return rx.IsMatch(emailaddress);
}
catch (FormatException)
{
return false;
}
}
UPDATE:
If you want to validate for a specific domain as you said in comments its even simpler:
Regex rx = new Regex(
#"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*#yourdomain.com$");
Replace yourdomain.com with your domain name.
Using the .Net mail namespace you can verify email address like this:
using System.Net.Mail;
private bool EmailVerify(string email)
{
try
{
var mail = new MailAddress(email);
return mail.Host.Contains(".");
}
catch
{
return false;
}
}
public static bool IsValidEmail(string emailaddress)
{
return new EmailAddressAttribute().IsValid(emailaddress);
}
// using System.ComponentModel.DataAnnotations;
If you are using
System.Net.Mail.SmtpClient
The most accurate way I've found is to attempt to create a
System.Net.Mail.MailAddress
object. If you cannot create the object with the address in your string it will throw one of the following:
ArgumentNullException // The address is null
ArgumentException // The address is string.Empty
FormatException // The address is not in a recognized format
https://msdn.microsoft.com/en-us/library/591bk9e8(v=vs.110).aspx
I've found that
Dns.GetHostEntry
is iffy at best. It does not seem to recognize multilayered domains as valid (domain.subdomain1.subdomain2.com), so checking the domain using that method is NOT definitive.
Using a RegEx is ok, but they often fail to recognize quoted addresses and other valid patterns (which are fine according to the RFC) as valid.
Since, to use the SmtpClient class you have to have a valid MailAddress object anyway, it just makes sense.
Here is an another way to check valid email address
public bool IsValidEmail(string email)
{
try
{
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}

X-Forwarded-For: How can I get the client's IP address in ASP.Net MVC?

I'm totally new to the asp.net mvc stack and i was wondering what happened to the Request.Header object?
Basically what I want to do is to pull out the Device(PC) IP address, but I fail to retrieve the desired output. I also tried Request.ServerVariables object but result always remain NULL.
I am using asp.net MVC. is there any change in this function required:
public static string GetIP()
{
string functionReturnValue = null;
//Gets IP of actual device versus the proxy (WAP Gateway)
functionReturnValue = HttpContext.Current.Request.Headers["X-FORWARDED-FOR"]; //functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
functionReturnValue = HttpContext.Current.Request.Headers["X-Forwarded-For"];//functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
// GetIP = Context.Request.ServerVariables("REMOTE_ADDR")
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
functionReturnValue = HttpContext.Current.Request.Headers["X-CLIENT-IP"];//functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
functionReturnValue = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];//functionReturnValue = "::1"
}
}
}
}
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("(\\d{1,3}\\.){3}\\d{0,3}");
if (functionReturnValue != null)
{
if (regex.IsMatch(functionReturnValue))
{
functionReturnValue = regex.Match(functionReturnValue).Value.ToString();
}
else
{
functionReturnValue = "";
}
regex = null;
}
if (functionReturnValue == null)
{
return "";
}
else
{
return functionReturnValue;
}
}
In X-Forwarded-For you will get client ip,proxy1 & proxy2. By taking first item you will get client/user ip.
HttpContext.Current.Request.Headers["X-Forwarded-For"].Split(new char[] { ',' }).FirstOrDefault()
Hope it helps!

User IP Address , Using Proxy or Not , Some Help [closed]

Please see the below codes :
private string GetUserIPAddress()
{
string User_IPAddress = string.Empty;
string User_IPAddressRange = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(User_IPAddressRange))//without Proxy detection
{
User_IPAddress = Request.ServerVariables["REMOTE_ADDR"];
//or
//Client_IPAddress = Request.UserHostAddress;
//or
//User_IPAddress = Request.ServerVariables["REMOTE_HOST"];
}
else////with Proxy detection
{
string[] splitter = { "," };
string[] IP_Array = User_IPAddressRange.Split(splitter,
System.StringSplitOptions.None);
int LatestItem = IP_Array.Length - 1;
User_IPAddress = IP_Array[LatestItem - 1];
//User_IPAddress = IP_Array[0];
}
return User_IPAddress;
}
In the case of :
1-
User_IPAddress = Request.ServerVariables["REMOTE_ADDR"];
and
Client_IPAddress = Request.UserHostAddress;
and
User_IPAddress = Request.ServerVariables["REMOTE_HOST"];
is the lower or middle line an alternate for the other lines?
Would you please give us some explain about these lines?
What are the differences ?
2-
User_IPAddress = IP_Array[LatestItem - 1];
and
User_IPAddress = IP_Array[0];
Which line should I use?
Would you please give explain about these lines?
I Don't know the class but chances are Request.UserHostAddress is an alias for Request.ServerVariables["REMOTE_ADDR"]. Also REMOTE_HOST would be the hostname but in most cases will just be the ipaddress.
Format of X-Forwarded-For is client1, proxy1, proxy2. So you want the second one. User_IPAddress = IP_Array[0];
Just remember "Since it is easy to forge an X-Forwarded-For field the given information should be used with care."

Categories

Resources