Iv'e recently started a new job as an ICT Technician and im creating an Console application which will consists of stuff that will help our daily tools!
My first tool is a Network Scanner, Our system currently runs on Vanilla and Asset tags but the only way we can find the hostname / ip address is by going into the Windows Console tools and nslookup which to me can be improved
I want to create an application in which I enter a 6 digit number and the application will search the whole DNS for a possible match!
Our hostsnames are like so
ICTLN-D006609-edw.srv.internal the d 006609 would be the asset tag for that computer.
I wish to enter that into the Console Application and it search through every hostname and the ones that contain the entered asset tag within the string will be returned along with an ip and full computer name ready for VNC / Remote Desktop.
Firstly how would I go about building this, shall i start the project of as a console app or a WPF. can you provide an example of how I can scan the hostnames via C#, or if there's an opensource C# version can you provide a link.
Any information would be a great help as it will take out alot of issues in the workpalce as we have to ask the customer to go into there My Computer adn properties etc and then read the Computer name back to use which I find pointless.
Regards.
Updates:
*1 C# Version I made: http://pastebin.com/wBWxyyuh
I would actually go about this with PowerShell, since automating tasks is kinda its thing. In fact, here's a PowerShell script to list out all computers visible on the network. This is easily translatable into C# if you really want it there instead.
function Find-Computer( [string]$assetTag ) {
$searcher = New-Object System.DirectoryServices.DirectorySearcher;
$searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry;
$searcher.SearchScope = 'Subtree';
$searcher.PageSize = 1000;
$searcher.Filter = '(objectCategory=computer)';
$results = $searcher.FindAll();
$computers = #();
foreach($result in $results) {
$computers += $result.GetDirectoryEntry();
}
$results.Dispose(); #Explicitly needed to free resources.
$computers |? { $_.Name -match $assetTag }
}
Here's a way you can accomplish this, although it's not the best. You might consider hitting Active Directory to find the legitimate machines on your network. The code below shows how you might resolve a machine name, and shows how to ping it:
static void Main()
{
for (int index = 0; index < 999999; index++)
{
string computerName = string.Format("ICTLN-D{0:000000}-edw.srv.internal", index);
string fqdn = computerName;
try
{
fqdn = Dns.GetHostEntry(computerName).HostName;
}
catch (SocketException exception)
{
Console.WriteLine(">>Computer not found: " + computerName + " - " + exception.Message);
}
using (Ping ping = new Ping())
{
PingReply reply = ping.Send(fqdn);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine(">>Computer is alive: " + computerName);
}
else
{
Console.WriteLine(">>Computer did not respond to ping: " + computerName);
}
}
}
}
Hope that helps...
Related
I am going crazy with an issue with LABEL of mapping a drive to windows with windows 7 OS. Scenario;
We need to map the drive as soon as user logs in to the machine. That seems to be working fine with other os versions except windows 7. Steps for windows 7;
EXE (c# made by us) launched in windows 7
EXE has mapped drive correctly
User logged out
Logged in back
Again exe is trying to map drive (Its registered as a startup exe)
The mapped drive label becomes "Network Drive" (Not sure how)
We are setting the proper values in registry as well as shown in below figure;
Problem is here;
Issue is only occurring when we do logout and login. If we manually launch exe, it works fine...
I have also tried to DELETE all these registry before mapping driving assuming it might be cache or something but nothing helped..
We are using zMapDrive to map a drive;
//create struct data
structNetResource stNetRes = new structNetResource();
stNetRes.iScope = 2;
stNetRes.iType = RESOURCETYPE_DISK;
stNetRes.iDisplayType = 3;
stNetRes.iUsage = 1;
stNetRes.sRemoteName = ls_ShareName;
stNetRes.sLocalName = ls_Drive;
//prepare params
int iFlags = 0;
if (lf_SaveCredentials) { iFlags += CONNECT_CMD_SAVECRED; }
if (lf_Persistent) { iFlags += CONNECT_UPDATE_PROFILE; }
if (ls_PromptForCredentials) { iFlags += CONNECT_INTERACTIVE + CONNECT_PROMPT; }
if (psUsername == "") { psUsername = null; }
if (psPassword == "") { psPassword = null; }
//if force, unmap ready for new connection
if (lf_Force) { try { zUnMapDrive(true); } catch { } }
//call and return
int i = WNetAddConnection2A(ref stNetRes, psPassword, psUsername, iFlags);
if (i > 0) { throw new System.ComponentModel.Win32Exception(i); }
Maybe a simple powershell script, renaming network drive will work for you? You can then use Task Scheduler to run it every time a user logs in.
$Rename = New-Object -ComObject Shell.Application
$Net = New-Object -ComObject WScript.Network
# map the drive if the path doesn't exist
If (!(Test-Path Z:))
{
$Net.MapNetworkDrive("Z:", '\\SERVER_ADDRESS\Directory', $false, "user", "password")
}
# change the drive name
$Rename.NameSpace("Z:\").Self.Name = "MyNetDriveLabel"
From my experience, support for network mapped drives is somewhat buggy in Windows 7, so I use similar workaround on a few of our Win7 machines.
iv made a web forum, as i have lots of folders on my local drive i can now search for any folders i want on webpage.
Now am looking to add a link to the results of the search so it takes me directly to the folder.
My code in c#:
protected void List_Dirs(string searchStr = null)
{
try
{
MainContentLocal.InnerHtml = "";
string[] directoryList = System.IO.Directory.GetDirectories("\\\\myfiles\\Web");
int x = 0;
foreach (string directory in directoryList)
{
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text = "Your Search for : <strong>" + SearchPhrase.Text + "</strong> returns ";
if(directoryP.ToLower().Contains(searchStr.ToLower()))
{
MainContentLocal.InnerHtml += directoryP + "<br />";
x++;
}
}
else
{
MainContentLocal.InnerHtml += directoryP + "<br />";
}
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text += "<strong>" + x.ToString() + "</strong> results";
UserInfo.CssClass = "userInfo";
}
}
catch(Exception DirectoryListExp)
{
MainContentLocal.InnerHtml = DirectoryListExp.Message;
}
}
When i enter something is search i will get a list of folders like:
Your Search for : project returns 2 results
job234 project234 Awards
job323 project game
now is there any way for me to click the result so i can open a window explore on the webpage
Thanks
You can create links like project234.
string folder = "\\\\myfiles\\Web";
if (string.IsNullOrWhiteSpace(Request["folder"])) {
// Folder clicked
folder = string.Format("{0}{1}", folder, Request["folder"]);
Process.Start(folder);
}
string[] directoryList = System.IO.Directory.GetDirectories(folder);
Then it will open it on the server. So if it really is local, than it will work. If there is no security problem. But I'm not sure. You can also use file:// links (as Ryan Mrachek notes), but browsers are not happy to let you open them.
If your result is a file, you can open that file programmatically through the Process class by invoking Process.Start("C:\\MyResults.txt"). This will open the results in the default text editor. In the same way, you can also open a web page by inserting passing a Url to Process.Start. I hope this is what wanted.
our file urls are malformed. It should be:
file:///c:/folder/
Please refer to The Bizarre and Unhappy Story of File URLs.
This works for me:
link
When you click Link, a new Windows Explorer window is opened to the specified location. But as you point out, this only works from a file:// URL to begin with.
A detailed explanation of what is going on can be found here. Basically this behavior by design for IE since IE6 SP1/SP2 and the only way you can change it is by explicitly disabling certain security policies using registry settings on the local machine.
So if you're an IT admin and you want to deploy this for your internal corporate LAN, this might be possible (though inadvisable). If you're doing this on some generic, public-facing website, it seems impossible.
How do you determine or examine the connection profile of the current network connection (if any)?
Specifically, I need to determine if the current connection is to a private or public network, and from there determine whether network discovery is turned on or off.
It seems like this information is readily available in a Windows Store app via the Windows.Networking.Connectivity.NetworkInformation.GetConnectionProfiles() or NetworkInformation.GetInternetConnectionProfile() functions, but this is a standard desktop app that must run on Win 7 and Server 2008 as well as Win 8 and Server 2012.
Enumerating the NICs on a machine is not a problem, but this doesn't solve my issue - I need to get the properties of the connection, not the physical device.
Is there an inbuilt way to do this with the .Net framework? Alternatively can it be done with WMI? Or as a crude alternative, can it be done by invoking the netsh command (although this seems to depend on the dot3svc and/or wlansvc services to be running)?
You can use Network List Manager API for that purpose, to use it from C# import Network List Manager Type Library.
Then you must enumerate all connected networks, because there can be more than one, for example right now I am connected to internet and VPN. Then for all connected networks call GetCategory() API, it returns NLM_NETWORK_CATEGORY (private, public or domain).
Here is the sample code (add using NETWORKLIST in use clauses) :
var manager = new NetworkListManager();
var connectedNetworks = manager.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED).Cast<INetwork>();
foreach (var network in connectedNetworks)
{
Console.Write(network.GetName() + " ");
var cat = network.GetCategory();
if (cat == NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PRIVATE)
Console.WriteLine("[PRIVATE]");
else if (cat == NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PUBLIC)
Console.WriteLine("[PUBLIC]");
else if (cat == NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_DOMAIN_AUTHENTICATED)
Console.WriteLine("[DOMAIN]");
}
Console.ReadKey();
For this to work one must add reference to COM Network List 1.0 Type Library, like this:
For Network Discovery you have to use Firewall API and reference COM library NetFwTypeLib and get INetFwProfile for active profile, then in services there are File sharing, Network Discovery and Remote Desktop services, and there is a bool flag if these are Enabled. Here is the example code : (just to warn you I didn't use below code in production I was just exploring this API)
Type objectType = Type.GetTypeFromCLSID(new Guid("{304CE942-6E39-40D8-943A-B913C40C9CD4}"));
var man = Activator.CreateInstance(objectType) as INetFwMgr;
/// get current profile
INetFwProfile prof = man.LocalPolicy.CurrentProfile;
Console.WriteLine("Current profile ");
ShowProfileServices(prof);
And the method that shows profile services.
private static void ShowProfileServices(INetFwProfile prof)
{
var services = prof.Services.Cast<INetFwService>();
var sharing = services.FirstOrDefault(sc => sc.Name == "File and Printer Sharing");
if (sharing != null)
Console.WriteLine(sharing.Name + " Enabled : " + sharing.Enabled.ToString());
else
Console.WriteLine("No sharing service !");
var discovery = services.FirstOrDefault(sc => sc.Name == "Network Discovery");
if (discovery != null)
Console.WriteLine(discovery.Name + " Enabled : " + discovery.Enabled.ToString());
else
Console.WriteLine("No network discovery service !");
var remoteDesktop = services.FirstOrDefault(sc => sc.Name == "Remote Desktop");
if (remoteDesktop != null)
Console.WriteLine(remoteDesktop.Name + " Enabled : " + remoteDesktop.Enabled.ToString());
else
Console.WriteLine("No remote desktop service !");
}
I know this question is super old, but I faced this problem recently - how to get Network Category (private or public) in C# using Windows.Network.Connectivity from Windows Runtime API.
There is almost everything related to networking but I could not find the Network Category.
The solution is NetworkTypes enum.
https://learn.microsoft.com/en-us/uwp/api/windows.networking.connectivity.networktypes?view=winrt-22000
Simply check if returned types has flag PrivateNetwork. If yes - then is't private, if not - it's public.
Example code below:
var adapters = NetworkInterface.GetAllNetworkInterfaces();
var upNetworkInterfaces = adapters.Where(x =>
x.Supports(NetworkInterfaceComponent.IPv4) &&
x.NetworkInterfaceType is NetworkInterfaceType.Ethernet or NetworkInterfaceType.Wireless80211);
foreach (var adapter in upNetworkInterfaces)
{
var hostname = NetworkInformation.GetHostNames()
.FirstOrDefault(x =>
x.IPInformation != null &&
string.Equals(x.IPInformation.NetworkAdapter.NetworkAdapterId.ToString(),
adapter.Id.Replace("{", string.Empty).Replace("}", string.Empty),
StringComparison.InvariantCultureIgnoreCase));
if (hostname is not null)
{
var networkTypes = hostname.IPInformation.NetworkAdapter.NetworkItem.GetNetworkTypes();
var privateNetwork = networkTypes.HasFlag(NetworkTypes.PrivateNetwork)
? NetworkAccessibilityLevel.Private
: NetworkAccessibilityLevel.Public;
}
}
I know similar questions have been asked a lot, ie "can I print from my wp8?". Most folks seem content with the simple "no" response. I am looking to add this functionality into my app and I know it can be accomplished at some level - even if I can only support a very minimum printer set for now.
I've looked at the app PrintHand, and it appears to have the capabilities I need: print to wireless and Bluetooth printers.
I've been looking through the Bluetooth scenarios document a bit and I think this might help discover a Bluetooth printer. That's a start. Perhaps it will help in identifying wireless printers also.
I realize I need to start very small with this project and I want to first try to enumerate any wireless printers (I don't have a Bluetooth one yet) available on the current network. Would anybody happen to have a pointer in the right direction on how to get started or better yet, some related sample code?
Thanks so much!
Best I can give is my Github Repo which isn't related to Wifi printers, but Google cloud printing.
There isn't really a .net reference for using Google Cloud Print in their documentation, but the code works in Mono, and should be easy to move over to .NET and hence, Windows Phone.
MonoGCP
I was able to detect a nearby wireless printer using Simple Service Discovery Protocol.
Here is my sample function:
private const string SSDP_IP = "239.255.255.250";
private const string SSDP_PORT = "1900";
public async static void DiscoverAsync2()
{
var multicastIP = new HostName(SSDP_IP);
var found = false;
using (var socket = new DatagramSocket())
{
socket.MessageReceived += (sender, e) =>
{
var reader = e.GetDataReader();
var bytesRemaining = reader.UnconsumedBufferLength;
var receivedString = reader.ReadString(bytesRemaining);
// TODO: something useful with this new info
found = true;
};
await socket.BindEndpointAsync(null, string.Empty);
socket.JoinMulticastGroup(multicastIP);
while (true)
{
found = false;
using (var stream = await socket.GetOutputStreamAsync(multicastIP, SSDP_PORT))
{
var request = new StringBuilder();
request.AppendLine("M-SEARCH * HTTP/1.1");
request.AppendLine("HOST: " + SSDP_IP + ":" + SSDP_PORT);
request.AppendLine("MAN: \"ssdp:discover\"");
request.AppendLine("MX: 3");
request.AppendLine("ST: urn:schemas-upnp-org:device:Printer:1"); // use ssdp:all to get everything
request.AppendLine(); // without this extra blank line, query won't run properly
var buff = Encoding.UTF8.GetBytes(request.ToString());
await stream.WriteAsync(buff.AsBuffer());
await Task.Delay(5000);
if (!found)
break;
}
}
}
Is there a toolkit/package that is available that I could use to find a list of wireless networks (SSID's) that are available in either Java, C#, or C for Windows XP+? Any sample code would be appreciated.
For C#, take a look at the Managed Wifi API, which is a wrapper for the Native Wifi API provided with Windows XP SP2 and later.
I have not tested this code, but looking at the Managed Wifi API sample code, this should list the available SSIDs.
WlanClient client = new WlanClient();
foreach ( WlanClient.WlanInterface wlanIface in client.Interfaces )
{
// Lists all available networks
Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList( 0 );
foreach ( Wlan.WlanAvailableNetwork network in networks )
{
Console.WriteLine( "Found network with SSID {0}.", GetStringForSSID(network.dot11Ssid));
}
}
static string GetStringForSSID(Wlan.Dot11Ssid ssid)
{
return Encoding.ASCII.GetString( ssid.SSID, 0, (int) ssid.SSIDLength );
}
ArrayList<String>ssids=new ArrayList<String>();
ArrayList<String>signals=new ArrayList<String>();
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "netsh wlan show all");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line.contains("SSID")||line.contains("Signal")){
if(!line.contains("BSSID"))
if(line.contains("SSID")&&!line.contains("name")&&!line.contains("SSIDs"))
{
line=line.substring(8);
ssids.add(line);
}
if(line.contains("Signal"))
{
line=line.substring(30);
signals.add(line);
}
if(signals.size()==7)
{
break;
}
}
}
for (int i=1;i<ssids.size();i++)
{
System.out.println("SSID name == "+ssids.get(i)+" and its signal == "+signals.get(i) );
}
Well, you didn't specify the OS so, for Linux I will suggest Wireless Tools for Linux by Jean Tourrilhes (http://www.hpl.hp.com/personal/Jean_Tourrilhes/Linux/Tools.html). The iwlist() command displays a lot of information about the available networks. The source code is in C. Another way is to write your own code in C using libpcap for capturing the beacon frames and extracting SSID from them (in monitor mode only). I haven't tested my sniffing code yet so I won't paste it here but it is pretty simple job.