Getting al ip's - c#

So, i'm new to C# and visual studio and stuff. But i searched arround for how to get all ip's, Like you see in the Windows Firewall app. But I can't find any thing to get started with. I saw alot of posts about Dns, And stuff So i got this:
private void ip()
{
StringBuilder sb = new StringBuilder();
// Get host name
String strHostName = Dns.GetHostName();
// Find host by name
IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
// Enumerate IP addresses
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
sb.AppendLine(strHostName + " - " + ipaddress);
label1.Text = sb.ToString().Replace(Environment.NewLine, "\n");
}
}
But I only get 4 ip's but i want all ip's currently connecting to my pc.
(And an i know there are alot of posts about this, but i'm searching for an answer for an beginning programmer to understand)
Could anybody help me?
Thanks!

That code you show gets the IPs assigned to the current machine.
What it sounds like you want is the equivalent of running netstat on the command line (get all active connections). This question should get you started: How to determine tcp port used by Windows process in C#
Basically you use GetActiveTcpConnections.

Related

Auto Detect The Application on LAN using C#.net

I have an Open Source Voice Chatting application which works fine on LAN.
But the problem is with connecting two PCs Manually.
Let's suppose there are two PCs (Application instances), PC A and PC B.
To make a connection I have to put the IP Address of the PC A into PC B and IP Address of the PC B into PC A.
I want to make the small code change where if the application is running on two PCs and they both are connected via LAN then both sides get the IP address automatically. Like auto-detection.
So my logic was to first know the IP Address on the LAN using arp -a command then writes the output in a text file and only obtain the IP addresses that start with 192... and check the instance of the application on each address using This Solution.
Unfortunately, I end up getting an error which states that.
Unhandled Exception: System.Runtime.InteropServices.COMException: The
RPC server is unavailable.
at
System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32
errorCode, IntPtr errorInfo) at
System.Management.ManagementScope.InitializeGuts(Object o) at
System.Management.ManagementScope.Initialize() at
System.Management.ManagementObjectSearcher.Initialize() at
System.Management.ManagementObjectSearcher.Get()
This is the code which i used to accomplish this task.
//Write the cmd Output in a text file
string strCmdText;
strCmdText = #"/K arp -a > C:\Test\Result.txt";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
//To get the IP address which starts with the 192.
const string ipPattern = #"^\s*(192\.168\.\d{1,3}\.\d{1,3}\b)";
var ipRegex = new Regex(ipPattern);
var ipAddresses192168 = File.ReadAllLines(#"C:\Test\Result.txt")
.Skip(3) // Skip 3 lines
.Where(line => ipRegex.IsMatch(line))
.Select(line => ipRegex.Match(line).Groups[1].Value);
foreach (var ipAddress in ipAddresses192168)
{
Console.WriteLine(ipAddress);
// Check for the running instance of the application on LAN network.
ManagementScope scope = new ManagementScope(#"\\" + ipAddress + #"\root\cimv2");
string query = "SELECT * FROM Win32_Process WHERE Name='WavPlayer.exe'";
var searcher = new ManagementObjectSearcher(query);
searcher.Scope = scope;
bool isRunning = searcher.Get().Count > 0;
}
So my question is, Is there any other straight forward process to accomplish this task using C#.net?
I am available to provide more info about this question so any help is appreciated.

failing to get IPv6 remotely

I am trying to fetch IPs of remote machine. But my code fails to collect IPv6 remotely. The code runs fine when run locally. Following is my sample code
System.Net.IPHostEntry hostEntryComputer;
try
{
hostEntryComputer = System.Net.Dns.GetHostEntry(computerName);
foreach (System.Net.IPAddress addr in hostEntryComputer.AddressList)
{
string temp = addr.ToString();
Console.WriteLine("IP: " + temp);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
any help would be appreciated.
From MSDN: "IPv6 addresses are filtered from the results of the GetHostEntry method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty IPHostEntry instance if only IPv6 results where available for the hostNameOrAddress.parameter."
Follow those tutorials to enable it on your local machine:
Windows XP
Windows Vista/7

NetAddresses always null in Win32_NetworkAdapter query

I am trying to get the active network adapter's IP address, so that I avoid virtual and other VPN adapters that are not connected at present.
On my current laptop the following code returns 3 IP V4 addresses, and I don't know how to get the "real", in use IP address from that list.
IPAddress[] ipV4Addresses = Array.FindAll(
Dns.GetHostEntry(String.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
Looking at MSDN doc here, I thought maybe I was on the right track. Has anyone obtained the list of IP addresses per adapter successfully? If so, please share your wisdom. Thanks!
This is all prototype at this point. I have this code (thanks to SO!), and the string[] netAddresses is always null, even with the computer connected to a network and with a functioning IP address.
string wmiQuery = "SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL";
ManagementObjectSearcher moSearch = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection moCollection = moSearch.Get();
foreach (ManagementObject mo in moCollection)
{
Console.WriteLine("{0} is {1}", mo["Name"], mo["NetConnectionStatus"]);
string[] netAddresses = (string[])mo["NetworkAddresses"];
if (netAddresses != null)
{
foreach (string netAddress in netAddresses)
{
Console.WriteLine("\tnet addresses:");
Console.WriteLine("\t\t{0}", netAddress);
}
}
}
from MS docs: http://msdn.microsoft.com/en-us/library/windows/desktop/aa394216%28v=vs.85%29.aspx
NetworkAddresses
Data type: string array
Access type: Read-only
Array of network addresses for an adapter. This property is inherited from CIM_NetworkAdapter.
This property has not been implemented yet. It returns a NULL value by default.
There's no such thing as a "real" IP address. Each packet you send is routed to its destination based on the metric of the adapter and the available routing paths. You can guess which IP is primarily being used for internet traffic by doing the following:
Order your adapters by metric, lowest first.
Prioritise WAN IPs, then 192.168.x.x, then 10.x.x.x, and totally ignore loopback addresses.
This will give you a guess as to the "preferred" address, though it's hardly definitive.
Look at WIn32_NetworkAdapterConfiguration, by using the InterfaceIndex from Win32_NetworkAdapter you should be able to get the configuration you need with the ipaddresses assigned to that nic.

InstallPrintQueue: how to create a new port? (.net,c#)

I'm fighting here with System.Printing namespace of .net framework.
And what i always saw as a wired thing in all the tools by MS to manage my printservers is they lack Port and Driver managing functionality.
So I'm stuck here with a piece of code that works:
PrintServer _ps = new PrintServer(PServer,
PrintSystemDesiredAccess.AdministrateServer );
_ps.InstallPrintQueue(QToCreate.Name, QToCreate.Driver,new string [] {"LPT1:"}, "winprint", PrintQueueAttributes.None);
And it does create a Queue for me on remote server, using the driver i specify, but driver should be there on server already which i can live with, but i failed to find a way to create new TCP/IP port on my print server, so installing new print queues this way can be something usable. i don't see why am i allowed to only install new queues with existing ports. kinda fails me. If somebody knows how to create a port along with a queue, i'd like to see how.
gah.. and when there is no hope - do research more
short answer - "you can't add a port using system.printing"
long answer - use wmi
vb sample follows:
Set objWMIService = GetObject("winmgmts:")
Set objNewPort = objWMIService.Get _
("Win32_TCPIPPrinterPort").SpawnInstance_
' Use IP of Printer or Machine sharing printer
objNewPort.Name = "IP_192.168.1.1"
objNewPort.Protocol = 1
objNewPort.HostAddress = "192.168.1.1"
' Enter Port number you would like to use
objNewPort.PortNumber = "9999"
objNewPort.SNMPEnabled = False
objNewPort.Put_

Identifying active network interface

In a .NET application, how can I identify which network interface is used to communicate to a given IP address?
I am running on workstations with multiple network interfaces, IPv4 and v6, and I need to get the address of the "correct" interface used for traffic to my given database server.
The simplest way would be:
UdpClient u = new UdpClient(remoteAddress, 1);
IPAddress localAddr = ((IPEndPoint)u.Client.LocalEndPoint).Address;
Now, if you want the NetworkInterface object you do something like:
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipProps = nic.GetIPProperties();
// check if localAddr is in ipProps.UnicastAddresses
}
Another option is to use P/Invoke and call GetBestInterface() to get the interface index, then again loop over all the network interfaces. As before, you'll have to dig through GetIPProperties() to get to the IPv4InterfaceProperties.Index property).
Neither of these will actually give the OP the info he's looking for -- he wants to know which interface will be used to reach a given destination. One way of doing what you want would be to shell out to the route command using System.Diagnostics.Process class, then screen-scrape the output. route PRINT (destination IP) will get you something useable. That's probably not the best solution, but it's the only one I can give you right now.
The info you are after will be in WMI.
This example using WMI may get you most of the way:
using System.Management;
string query = "SELECT * FROM Win32_NetworkAdapterConfiguration";
ManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);
ManagementObjectCollection moCollection = moSearch.Get();// Every record in this collection is a network interface
foreach (ManagementObject mo in moCollection)
{
// Do what you need to here....
}
The Win32_NetworkAdapterConfiguration class will give you info about the configuration of your adapters e.g. ip addresses etc.
You can also query the Win32_NetworkAdapter class to find out 'static'about each adapter (max speed, manufacturer etc)
At least you can start with that, giving you all addresses from dns for the local machine.
IPHostEntry hostEntry = Dns.GetHostEntry(Environment.MachineName);
foreach (System.Net.IPAddress address in hostEntry.AddressList)
{
Console.WriteLine(address);
}
Just to give a complete picture: another approach would be to use Socket.IOControl( SIO_ROUTING_INTERFACE_QUERY, ... )
ConferenceXP includes rather comprehensive function wrapping this, works with IPv4/6 and multicast addresses: https://github.com/conferencexp/conferencexp/blob/master/MSR.LST.Net.Rtp/NetworkingBasics/utility.cs#L84

Categories

Resources