we have 10 computers at lab, we set-up all computers connected to LAN so we
can share files, my computer serves as the main computer, i just want to get all
IP address of the computers connected to main computer(that is my computer) and list them
my code is
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd ";
p.StartInfo.UseShellExecute = false;
p.StartInfo.Arguments = "/C net view";
p.StartInfo.RedirectStandardOutput = true;
p.Start();
String output = p.StandardOutput.ReadToEnd();
char[] delimiters = new char[] { '\n', '\\' };
string[] s = output.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string hostName = Dns.GetHostName();
IPHostEntry IPHost = Dns.GetHostEntry(hostName);
Console.WriteLine(IPHost.HostName); // Output name of web host
IPAddress[] address = IPHost.AddressList; // get list of IP address
// Console.WriteLine("List IP {0} :", IPHost.HostName);
if (address.Length > 0)
{
for (int i = 0; i < address.Length; i++)
{
Console.WriteLine(address[i]);
}
}
p.WaitForExit();
int z = s.Length - 5;
string[] str1 = new string[z];
// int i = 0;
char[] saperator = { ' ' };
for (int j = 3; j < s.Length - 2; j++)
{
//Console.WriteLine(s[i]);
// str1[i] = (s[j].ToString()).Split(saperator)[0];
// Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
//Console.WriteLine(output);
s = output.Split(new string[] { "\n,\\" }, StringSplitOptions.None);
//Console.WriteLine(s[i]);
//Console.WriteLine(output);
// Console.WriteLine("IP Address : {1} ", i, AddressList[i].ToString());
Console.ReadLine();
but i get my machine's ip address ,i want to 10 machine's ip address in lab.
Instead of passing the host name, pass the result of net view.
foreach (string hostName in hostNames)
{
//string hostName = Dns.GetHostName();
IPHostEntry entry = Dns.GetHostEntry(hostName);
Console.WriteLine(entry.HostName); // output name of web host
IPAddress[] addresses = entry.AddressList; // get list of IP addresses
foreach (var address in addresses)
{
Console.WriteLine(address);
}
}
Related
I stumble on the following problems:
When trying to use the Parallel Function. I need to synchronously wait until the all the information is gathered.
When I put the foreach loop inside the try there are duplicate values.
How can I fix this? I want when I scan a subnet (254 hosts) that I get live results back.
Code:
//Network Information Parallel.ForEach Example
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Text;
namespace AsteRScanneR
{
public class Program1
{
public static void Main()
{
Console.WriteLine("Enter IP Adresses seperated by a comma!");
Console.Write("Enter IP Adresses: ");
List<string> ipAdresses = new List<string>();
ipAdresses = Console.ReadLine().Split(',').ToList();
var firstOrDefault = ipAdresses.FirstOrDefault();
string[] octets = firstOrDefault.Split('.');
if (octets[3] == string.Empty)
{
ipAdresses = new List<String>();
for (int i = 1; i < 255; i++)
{
var result = String.Concat(firstOrDefault, i.ToString());
ipAdresses.Add(result);
}
}
else
{
Console.WriteLine("Multiple IP's Found!");
}
//In case you want to scan a whole subnet, user needs to input only the ABC of the IP adres and leave the D empty. It will scan 255 hosts
//Options
PingOptions pingOptions = new PingOptions(128, true);
int timeout = 1000;
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
List<PingReply> pingRepliesList = new();
Parallel.ForEach(ipAdresses, ip =>
{
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = CancellationToken.None };
try
{
Stopwatch sw = new Stopwatch();
sw.Start();
Ping p = new();
lock (pingRepliesList) {
pingRepliesList.Add(p.Send(ip, timeout, buffer, pingOptions));
}
sw.Stop();
//Console.WriteLine("Pinging: "+ip+" took: "+sw.Elapsed.Milliseconds+"ms on Thread:"+ Environment.CurrentManagedThreadId);
}catch (Exception)
{
Console.WriteLine("An Error Occured...");
}
});
Console.WriteLine("");
foreach (var pingvalue in pingRepliesList)
{
if (pingvalue.Status == IPStatus.Success)
{
Console.WriteLine("Pinging " + pingvalue.Address.ToString() + " with " + pingvalue.Buffer.Length + " bytes of data:");
Console.WriteLine("Reply from " + pingvalue.Address.ToString() + ": bytes=" + pingvalue.Buffer.Length + " time" + pingvalue.RoundtripTime + "ms TTL=" + pingvalue.Options.Ttl);
Console.WriteLine("");
}
else
{
Console.WriteLine("Pinging " + pingvalue.Address.ToString() + " with " + pingvalue.Buffer.Length + " bytes of data:");
Console.WriteLine("General failure.");
Console.WriteLine("");
}
}
}
}
}
I found the solution to the problem. This is what I did:
Used the example code from: https://riptutorial.com/csharp/example/3279/parallel-for
Replacing the hard-coded list with for now the user-input. (This will be changed to args user input afterwards.)
Included the piece of code I wrote down below
Console.WriteLine("Enter IP Adresses seperated by a comma!");
Console.Write("Enter IP Adresses: ");
List<string> ipAdresses = new List<string>();
ipAdresses = Console.ReadLine().Split(',').ToList();
var firstOrDefault = ipAdresses.FirstOrDefault();
string[] octets = firstOrDefault.Split('.');
if (octets[3] == string.Empty)
{
ipAdresses = new List<String>();
for (int i = 1; i < 255; i++)
{
var result = String.Concat(firstOrDefault, i.ToString());
ipAdresses.Add(result);
}
}
else
{
Console.WriteLine("Multiple IP's Found!");
Console.WriteLine("");
}
Changed Parallel.For loop to .Count, because I am using a List
Changed some output result.Address.ToString() to ipAdresses[i] because it was creating bugs and displaying the same output over and over again.
Formatted everything in 1 string to not stumble upon problems.
I did format in 1 string on purpose, because when I formatted two strings I to get output mixed.
I am currently making a client and server. The server will store people and their location using a dictionary. The client can then lookup a location or update/add a person and their location. For example, I could type 'Lucy', 'School', and the server will add that to the dictionary. If I then type 'Lucy' it should reply with 'School' and if I type in 'Lucy' 'Home' it should up date that to the dictionary.
However, in the arguments, the user may put /h followed by a host name and /p followed by a port number. I'm currently trying to implement this feature in the client, however it doesn't seem to be working at all.
The following is my code. I made a list for the arguments so that if it does have /h or /p followed by the appropriate information, I can reduce the number of arguments so it doesn't effect the other parts of the program.
static void Main(string[] args)
{
String server = "whois.networksolutions.com";
int port = 43;
List<string> list = new List<string>(args);
for (int i = 0; i < args.Length; i++)
{
if (args[i].Trim() == "/h")
{
string serverString = args[i + 1].Trim();
server = args[i + 1];
list.RemoveAt(i);
//remove h from the list
list.RemoveAt(i);
//remove server name from the lst
args = list.ToArray();
//update args array
i = i - 1;
Console.WriteLine("Server changed to " + serverString);
}
else if (args[i].Trim() == "/p")
{
string portString = args[i + 1];
port = Convert.ToInt32(args[i + 1].Trim());
list.RemoveAt(i);
//remove p from the list
list.RemoveAt(i);
//remover port number from list
args = list.ToArray();
//update args array
i = i - 1;
Console.WriteLine("Port changed to " + portString);
}
}
try
{
TcpClient client = new TcpClient();
client.Connect(server, port);
client.ReceiveTimeout = 1000;
client.SendTimeout = 1000;
StreamWriter sw = new StreamWriter(client.GetStream());
StreamReader sr = new StreamReader(client.GetStream());
sw.AutoFlush = true;
sw.WriteLine(args[0]);
if (args.Length == 1)
{
if (args[0] == "514872")
{
Console.WriteLine("514872 is being tested\r\n");
}
else
{
Console.WriteLine("ERROR: no entries found\r\n");
}
}
else if (args.Length == 2)
{
Console.WriteLine(args[0] + " location changed to be is being tested\r\n");
}
}
catch
{
Console.WriteLine("Connection failure.");
}
}
}
Any help would be massively appreciated!
Thank you
Lucy
Hello I have a question i'm trying to get all ip addresses of an nslookup domain. I'm using the following script in c# on a button but it only prints out 1 ip address, what am I doing wrong?
string myHost = "domain.com";
string myIP = null;
for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
{
if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
{
//myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
txtIp.Text = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
}
}
All help would be greatfull because I've seen mutiple answers here on stackoverflow but I can't get one to work properly.
regards,
Dennis
First of all, you should avoid making the dns request 3 times. Store the result in a variable.
Second, you set txtIp.Text to the last entry. You need to append the strings, but you replace them. Try this code:
string myHost = "domain.com";
string myIP = null;
IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(myHost);
for (int i = 0; i <= hostEntry.AddressList.Length - 1; i++)
{
if (!hostEntry.AddressList[i].IsIPv6LinkLocal)
{
txtIp.Text += hostEntry.AddressList[i].ToString();
}
}
But this can still be shortened to this:
string myHost = "domain.com";
string myIP = null;
IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(myHost);
txtIP.Text = string.Join(", ", hostEntry.AddressList.Where(ip => !ip.IsIPv6LinkLocal).Select(ip => ip.ToString()));
This gives you a comma-separated list of the ip addresses.
I have code, which find my NIC card IP address, IP subnet, Gateway, Mac and network card name (description). But the problem is, I have multiple NIC cards and WiFi on my PC. And this program instead of 4 NIC cards shows me only one primary.
How can solve this problem ?
public void NIC_data()
{
ManagementObjectSearcher query = new
ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
string[] addresses = (string[])mo["IPAddress"];
string[] subnets = (string[])mo["IPSubnet"];
string[] defaultgateways = (string[])mo["DefaultIPGateway"];
textBox1.Text = string.Format("Network Card: {0}", mo["Description"]);
textBox2.Text = string.Format(" MAC Address: {0}", mo["MACAddress"]);
foreach (string ipaddress in addresses)
{
textBox3.Text = string.Format(" IP Address: {0}", ipaddress);
}
foreach (string subnet in subnets)
{
textBox4.Text = string.Format(" Subnet Mask: {0}", subnet);
}
foreach (string defaultgateway in defaultgateways)
{
textBox5.Text = string.Format(" Gateway: {0}", defaultgateway);
}
}
You just assign the last value of the loop to textBoxes like textBox3.Text = .....
either append to textBox3.Text += ... or use a combo box.
How can I get the computer name and IP address of my PC programmatically? For example, I want to display that information in a text box.
Have a look at this: link
and this: link
textBox1.Text = "Computer Name: " + Environment.MachineName
textBox2.Text = "IP Add: " + Dns.GetHostAddresses(Environment.MachineName)[0].ToString();
Check more about this : How To Get IP Address Of A Machine
System.Security.Principal.WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
string strName = p.Identity.Name;
To get the machine name,
System.Environment.MachineName
or
using System.Net;
strHostName = DNS.GetHostName ();
// Then using host name, get the IP address list..
IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
IPAddress [] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString ());
}
In easy way..
string IP_Address = Dns.GetHostByName(Environment.MachineName).AddressList[0].toString();
I use the following found at: https://stackoverflow.com/a/27376368/2510099
for the IP address
public string GetIPAddress()
{
string ipAddress = null;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530); //Google public DNS and port
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
ipAddress = endPoint.Address.ToString();
}
return ipAddress;
}
and for the machine name
Environment.MachineName;