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;
Related
I am trying to create a GUI to an ESP8266 project that I have already developed. The boards are using the NodeMCU firmware, and I am loading programs on through the ESP8266 Arduino Core. I am using C# for my GUI program on Windows.
Here is my debug code for the ESP8266 (in Arduino):
#include <ESP8266WiFi.h>
String ConnectedMAC[8];
IPAddress ConnectedIP[8];
WiFiClient clientforcom;
void setup() {
WiFi.mode(WIFI_AP_STA);
Serial.begin(9600);
int f = WiFi.scanNetworks();
Serial.println("Scanning Networks");
delay(5000);
for (int n = 0; n < f; n++) {
Serial.println(WiFi.SSID(n));
}
WiFi.begin(ssid, passtring); //SSID and passtring are my home network credentials
delay(2000);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.print("The IP of this node is: ");
Serial.println(WiFi.localIP());
}
void loop() {
MACManagement();
WiFiServer serverforclient(WiFi.localIP(), 25565);
while (!serverforclient.hasClient()) { //this does not work with Socket or delay is too long
delay(50);
Serial.println("Waiting for client");
}
clientforcom = serverforclient.available();
while (clientforcom.available() <= 0) {
delay(50);
Serial.println("Waiting for response");
}
String response = clientforcom.readString();
if (response.startsWith("GetController")) {
Serial.println("Sending String");
clientforcom.println("Returned String");
}
}
void MACManagement() {
unsigned char number_client;
struct station_info *stat_info;
struct ip_addr *IPaddress;
IPAddress address;
int i = 0;
number_client = wifi_softap_get_station_num();
stat_info = wifi_softap_get_station_info();
Serial.print(" Total Connected Clients are = ");
Serial.println(number_client);
while (stat_info != NULL) {
IPaddress = &stat_info->ip;
address = IPaddress->addr;
Serial.print("client= ");
Serial.print(i);
Serial.print(" IP adress is = ");
Serial.print((address));
ConnectedIP[i] = address;
Serial.print(" with MAC adress is = ");
Serial.print(stat_info->bssid[0], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[1], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[2], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[3], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[4], HEX); Serial.print(" ");
Serial.print(stat_info->bssid[5], HEX); Serial.print(" ");
ConnectedMAC[i] = String(stat_info->bssid[0], HEX) + ":" + String(stat_info->bssid[1], HEX) + ":" + String(stat_info->bssid[2], HEX) + ":" + String(stat_info->bssid[3], HEX) + ":" + String(stat_info->bssid[4], HEX) + ":" + String(stat_info->bssid[5], HEX);
stat_info = STAILQ_NEXT(stat_info, next);
i++;
Serial.println();
}
}
and here is my network accessing code in C#:
void loadUI(){
enterIPLabel.Visible=false;
errorBox.Text="Connecting to Leader node";
tcpcom=new TcpClient(leadernode.ToString(),25565);
tcpcom.Connect(leadernode.ToString(),25565);
while(!tcpcom.Connected);
tcpcom.Client.Send(System.Text.Encoding.ASCII.GetBytes("GetController"));
errorBox.Text="Awaiting Node Response";
while(tcpcom.Available<=0); //hopefully this should stop this method from executing until the response is made
//FILL IN CODE FOR RETURN STATEMENT
tabController.Visible=true;
NodeMap.Visible=true;
}
However, when I reach the "Waiting for Client" section of the ESP8266 code and I run the C# program, entering the IP Address into leadernode. I get an error from .NET that states:
System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it
I have no idea why the ESP8266 would be refusing the connection, I put delays such that the Software Watch Dog would not initiate, so I don't understand why it would break the program.
This is the code I have:
/*
* This is a C# Program which displays the URL of an input IP address.
*/
using System;
using System.Net;
namespace CNT4704L
{
class MySocketLab
{
static void Main()
{
Console.Write("Enter an IP address (e.g., 131.247.2.211): ");
IPAddress addr = Console.ReadLine();
string strSiteName = Dns.GetHostEntry(addr);
Console.Write("\nHost name of ", addr);
Console.Write(" is ", strSiteName);
}
}
}
It says I can't implicitly convert type string to System.Net.IPAddress, but I'm not sure what the Url I'm trying to get could be other than a string.
Your problem is on this line:
IPAddress addr = Console.ReadLine();
The Console.ReadLine function returns a string not a IPAddress.
Just change it to:
var addr = Console.ReadLine();
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 to change IP address very frequently for playing LAN games as well as for using internet at home. I am creating an application in C# which can do it quickly. I have made fields like Adapter Name, IP Address, Subnet, DNS Server Address.
My code which runs on set IP button click is below:
string adapter = comboAdapterName.Text;
string ip = comboIPAddress.Text;
string subnet = comboSubnet.Text;
string dns = comboDNS.Text;
Now I want to use this process method for taking data from those fields and append the string accordingly.
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address \"Local Area Connection\" static 192.168.0.10 255.255.255.0 192.168.0.1 1");
p.StartInfo = psi;
p.Start();
But I guess it is not so easy. Because I am unable to edit this without disturbing the format. Also I tried creating a whole new string using many +s which i can place like:
ProcessStartInfo psi = new ProcessStartInfo(mystring);
But still it is too difficult for me. Please suggest an easy way to do this.
==========================================================================
I think I got it:
string ipstring = "netsh interface ip set address " + "\"" + adapter + "\"" + " " + "static" + " " + ip + " " + subnet + " " + dns;
You will need to use the String.Format method.
Example:
string subnet = comboSubnet.Text;
string formatted = string.Format("Subnet is: {0}", subnet);
MessageBox.Show(formatted);
Format that string to look like whatever you want.
You can get the current adapter config with following function:
private static void EthernetInf(out string ip, out string dns, out string nic) // To get current ethernet config
{
ip = "";
dns = "";
nic = "";
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (IPAddress dnsAdress in ni.GetIPProperties().DnsAddresses)
{
if (dnsAdress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
dns = dnsAdress.ToString();
}
}
foreach (UnicastIPAddressInformation ips in ni.GetIPProperties().UnicastAddresses)
{
if (ips.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !ips.Address.ToString().StartsWith("169")) //to exclude automatic ips
{
ip = ips.Address.ToString();
nic = ni.Name;
}
}
}
}
Following Function is used to set the IP in elevated command prompt:
private void SetIP(Button sender, string arg) //To set IP with elevated cmd prompt
{
try
{
if (sender.Background == Brushes.Cyan )
{
MessageBox.Show("Already Selected...");
return;
}
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
psi.UseShellExecute = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.Verb = "runas";
psi.Arguments = arg;
Process.Start(psi);
if (sender == EthStatic || sender == EthDHCP )
{
EthStatic.ClearValue(Button.BackgroundProperty);
EthDHCP.ClearValue(Button.BackgroundProperty);
sender.Background = Brushes.Cyan;
}
if (sender == WIFIStatic || sender == WIFIDhcp)
{
WIFIStatic.ClearValue(Button.BackgroundProperty);
WIFIDhcp.ClearValue(Button.BackgroundProperty);
sender.Background = Brushes.Cyan;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
This click button code passes the arguments to processstartinfo to set the IP
private void EthStatic_Click(object sender, RoutedEventArgs e)
{
SetIP(EthStatic, "/c netsh interface ip set address \"" + EthName + "\" static " + Properties.Settings.Default.EthIPac + " " + Properties.Settings.Default.Subnet + " " + Properties.Settings.Default.EthDnsac + " & netsh interface ip set dns \"" + EthName + "\" static " + Properties.Settings.Default.EthDnsac);
}
The complete app is available at:
https://github.com/kamran7679/ConfigureIP
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);
}
}