C# SimpleWifi can't connect to an unknown network - c#

I can't connect to wifi networks that the PC doesn't know. If I manually connect first, then the program is able to connect programmatically as long as I don't click on "Forget".
If the network is not known then the ap.Connect(authRequest) returns null.
How can I connect to a wifi network programmatically that the pc doesn't know yet?
var accessPoints = wifi.GetAccessPoints();
List<string> accessPointNames = new List<string>();
foreach (AccessPoint ap in accessPoints)
{
accessPointNames.Add(ap.Name);
string fSSID = "test1234";
if (ap.Name == fSSID)
{
AuthRequest authRequest = new AuthRequest(ap)
{
Password = "12345678"
};
if (ap.Connect(authRequest))
Console.WriteLine("connected");
else
Console.WriteLine("disconnected");
break;
}
}

Related

How to connect WPA2-Enterprise authentication network in window application?

I have created wifi scanner in .net c# window application. Right now i'm able to connect to WPA2-Personal authentication network.Now i want to connect with WPA-Enterprise Network but i'm not getting any idea how to connect to it.
Please if you have any solution so let me know
Below is my code for WPA2-Personal which is working
WlanClient client = new WlanClient();
foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
{
Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);
foreach (Wlan.WlanAvailableNetwork network in networks)
{
Wlan.Dot11Ssid ssid = network.dot11Ssid;
string networkName = Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
ListViewItem item = new ListViewItem(networkName);
item.SubItems.Add(network.dot11DefaultCipherAlgorithm.ToString());
item.SubItems.Add(network.wlanSignalQuality + "%");
item.SubItems.Add(network.dot11DefaultAuthAlgorithm.ToString());
listView1.Items.Add(item);
}
string profileName = "Network"; // this is also the SSID
string macA = "MAC_ADDRESS";
string key = "PASSWORD";
string profileXml = string.Format("<?xml version=\"1.0\" encoding=\"US-ASCII\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{0}</name><SSIDConfig><SSID><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><autoSwitch>false</autoSwitch><MSM><security><authEncryption><authentication>WPAPSK</authentication><encryption>TKIP</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType><protected>false</protected><keyMaterial>{1}</keyMaterial></sharedKey></security></MSM></WLANProfile>", profileName, key); //WPA-PSK
wlanIface.SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, true);
wlanIface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName);
}

C# Get IP of Remote Computer on Separate DNS Server

I am working on a utility for managing multiple computers in a specified domain (not necessarily the domain the computer the application is running on is a member of) within a specified directory root. The problem I am running into is once I have the collection of computer names from the external AD OU, I am unable to manage based on computer name because of DNS. Is it possible to perform DNS lookup on an external DNS server provided the IP of DNS server and credentials for that domain?
Here is the code that I have for the initialization process (works within the same domain). Really appreciate any input!
private Task InitializeComputers()
{
try
{
Computers.Clear();
object cLock = new object();
PrincipalContext context = new PrincipalContext(ContextType.Domain, CurrentConfiguration.LDAPAddress,
CurrentConfiguration.DirectoryRoot, ContextOptions.Negotiate,
CurrentConfiguration.AdminUser, CurrentConfiguration.AdminPassword);
ComputerPrincipal computer = new ComputerPrincipal(context);
computer.Name = "*";
PrincipalSearcher searcher = new PrincipalSearcher(computer);
PrincipalSearchResult<Principal> result = searcher.FindAll();
Parallel.ForEach(result, (r) =>
{
ComputerPrincipal principal = r as ComputerPrincipal;
DirectoryObject cObject = new DirectoryObject(CurrentConfiguration)
{
Name = principal.Name
};
lock (cLock)
{
Computers.Add(cObject);
}
});
}
... // Catch stuff here
}
private async Task InitializeConnections()
{
Task[] tasks = Computers.Select(x => x.CheckConnectionAsync()).ToArray();
await Task.WhenAll(tasks);
}
// This is where I need to be able to get the IP Address. Thoughts???
public Task CheckConnectionAsync()
{
return Task.Run(() =>
{
try
{
Ping PingCheck = new Ping();
PingReply Reply = PingCheck.Send(Name); // <--- need IP Address instead
if (Reply.Status == IPStatus.Success)
{
IsAvailable = true;
IPHostEntry host = Dns.GetHostEntry(Name); // Does not work for machines on different domain.
IPAddress = host.AddressList.FirstOrDefault().ToString();
}
else
{
IsAvailable = false;
IsWMIActive = false;
}
}
... // catch stuff here ...
});
}
To follow up, the solution that I found is derived from Heijden's DNS Resolver. I wrote a simple DnsManager class with a single static GetIPAddress method for extracting the IP out of an A Record.
public static string GetIPAddress(string name)
{
Resolver resolver = new Resolver();
resolver.DnsServer = ((App)App.Current).CurrentConfiguration.DNSAddress;
resolver.Recursion = true;
resolver.Retries = 3;
resolver.TimeOut = 1;
resolver.TranportType = TransportType.Udp;
Response response = resolver.Query(name, QType.A);
if (response.header.ANCOUNT > 0)
{
return ((AnswerRR)response.Answer[0]).RECORD.ToString();
}
return null;
}
Then, the updated CheckConnectionAsync method is now written like so:
public Task CheckConnectionAsync()
{
return Task.Run(() =>
{
try
{
IPAddress = DnsManager.GetIPAddress(Name + "." + CurrentConfig.DomainName);
... // check availability by IP rather than name...
}
// catch stuff here...
});
}
As soon as you plan to query dedicated server as DNS source, you have to step aside from default libs. I tried this (if remember correctly) once investigating dedicated DNS requests:
http://www.codeproject.com/Articles/12072/C-NET-DNS-query-component

Simple Net Scanner Only works Wireless but not wired

I found this C# code for simple IP net scanner which scans the connected hosts in the network and displays its physical address and IP address.It works well but only when connected with the network via WIFI. It doesn't work when connected through the network via wires.
[DllImport("iphlpapi.dll", ExactSpelling = true)]
At first, iphlpapi.dll has been imported. So, can you explain it? the rest of the code is given below.
// Use Your work Group WinNT://&&&&(Work Group Name)
DirectoryEntry DomainEntry = new DirectoryEntry("WinNT://" + this.TxtWorkGroup.Text.Trim());
DomainEntry.Children.SchemaFilter.Add("computer");
// To Get all the System names And Display with the Ip Address
foreach (DirectoryEntry machine in DomainEntry.Children)
{
string[] Ipaddr = new string[3];
Ipaddr[0] = machine.Name;
System.Net.IPHostEntry Tempaddr = null;
try
{
Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByName(machine.Name);
}
catch (Exception)
{
MessageBox.Show("Unable to connect with the system :" + machine.Name);
continue;
}
IPAddress[] TempAd = Tempaddr.AddressList;
foreach (IPAddress TempA in TempAd)
{
Ipaddr[1] = TempA.ToString();
byte[] ab = new byte[6];
int len = ab.Length;
// This Function Used to Get The Physical Address
int r = SendARP((int)TempA.Address, 0, ab, ref len);
string mac = BitConverter.ToString(ab, 0, 6);
Ipaddr[2] = mac;
}
ListViewItem TempItem = new ListViewItem(Ipaddr);
this.ListHostIP.Items.Add(TempItem);
}
}
Turn off the WIFI adapter and try it again.

Udp packets to machine behind nat

First of all sry about my english. My problem is i have electronic circuit on press machine. This circuit sending data to my server without a problem. After i recieve data i need to send command to circuit. In LAN its working like a charm. But out of lan circuit dont recieving my command somehow. Any idea how i can send to udp pocked to machine behind NAT ? my code is bellow , ty for any help.
private void ReceiveMessage()
{
while (true)
{
try
{
var remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
var content = _udpClient.Receive(ref remoteIpEndPoint);
if (content.Length > 0)
{
var message = Encoding.ASCII.GetString(content);
var smsg = message.Split('|');
var pin1 = int.Parse(smsg[13]);
var pin2 = int.Parse(smsg[14]);
var isChanged = CheckChanges(smsg[1]);
if (isChanged == 1)
{
**var recvpt = new IPEndPoint(remoteIpEndPoint.Address, remoteIpEndPoint.Port);
var client = new UdpClient();
var cmd1 = "CP1S" + _pin1Time + "F";
var cmd2 = "CP2S" + _pin2Time + "F";
var senddata1 = Encoding.UTF8.GetBytes(cmd1);
var senddata2 = Encoding.UTF8.GetBytes(cmd2);
client.Send(senddata1, senddata1.Length, recvpt);
client.Send(senddata2, senddata2.Length, recvpt);
client.Close();**
// UpdateChanges(smsg[1]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToStrin<wbr ></wbr>g());
}
}
}
}
Computers that are behind a NAT router are not directly accessible from a remote network. There would need to be rules put in place on your firewall/router to route this traffic to the remote machine. For explicit directions see your WAN/LAN admin. If you don't have one you could try asking over on Server Fault with more information about your network.

Detecting a SQL cluster

I am trying to write some code that will determine if a list of SQL servers are up. I have tried to WMI, SQLDMO, SqlDataSourceEnumerator, and Pinging port 1433 of each server, with varying degrees of success (see results below).
Using SQLDMO and SqlDataSourceEnumerator, i found 3 out of 6, it has to be said that 2 of the 3 missing SQL servers form a cluster.
Pinging port 1433 found 4 out of the 6, the 2 missing are the 2 servers that form the SQL cluster.
WMI proved to be the least successful, in that it only found 1 out of 6 servers.
Here is the code I used to prototype the server discovery:
private void buildServerMap(bool useLibCOM)
{
sqlServersMap = new Dictionary<string, string>();
if (useLibCOM)
{
//get all available SQL Servers
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
SQLDMO.NameList sqlServers = sqlApp.ListAvailableSQLServers();
ArrayList servs = new ArrayList();
for (int i = 0; i < sqlServers.Count; i++)
{
object srv = sqlServers.Item(i + 1);
if (srv != null)
{
sqlServersMap.Add(srv.ToString(), srv.ToString());
}
}
}
else
{
System.Data.Sql.SqlDataSourceEnumerator enumSQL = System.Data.Sql.SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = enumSQL.GetDataSources();
foreach (System.Data.DataRow row in table.Rows)
{
foreach (System.Data.DataColumn col in table.Columns)
{
sqlServersMap.Add((string)row[col], (string)row[col]);
}
}
}
}
private bool pingSqlServer(string server)
{
bool success = false;
TcpClient client = new TcpClient();
try
{
client.Connect(server, 1433);
success = true;
}
catch (Exception)
{
//throw;
}
return success;
}
public StringBuilder buildWmiServerList(string path, string sqlServer, string sqlServerServiceName, StringBuilder sb, out bool reportNeeded)
{
reportNeeded = false;
try
{
ManagementScope ms = new ManagementScope(path);
ms.Connect();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service WHERE Started = TRUE AND DisplayName='" + sqlServerServiceName + "'");
searcher.Scope = ms;
if (searcher != null && searcher.Get() != null)
{
foreach (ManagementObject service in searcher.Get())
{
sb.Append(sqlServer + " SQL Server service - RUNNING\n");
}
}
}
catch (Exception e)
{
sb.Append(sqlServer + " SQL Server service - UNVERIFIABLE\n");
reportNeeded = true;
}
return sb;
}
Any ideas in how to resolve/detect SQL servers that form a SQL cluster?
i don't know about DMO which is deprecated anyway but in SMO you can do Server.IsClustered.
you may also want to look at this:
http://www.sqldbatips.com/showarticle.asp?ID=45
Why not try SQL ping? There is source code here so you can see how they do it.
Anyway, some thoughts:
Are you trying the the physical server, the cluster name, or the virtual server name(s) eg phys1, phys2, vclus, vserv1, vserv2 (assuming active/active)?
Are you using tcp or named pipes from your client? Have you tried tcp:vserv1?
Named pipes can be funny on clusters IIRC if disabled then enabled, for example.
The protocols used are listed in the SQL logs, as well as the tcp port that is used (named instance = random)
Can you create a system DSN on your client? From this, you can work out what port and protocol is used under HKLM\SW\Microsoft\MSSQLServer

Categories