get MAC address of computer - c#

I want to accesss the mac address of the computer using c#. I have used the following code to access mac address but there is some issue in this code.
Code 1
foreach( NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces() )
{
if( nic.OperationalStatus == OperationalStatus.Up )
{
Console.WriteLine( nic.GetPhysicalAddress().ToString() );
checkMAC = nic.GetPhysicalAddress().ToString();
break;
}
}
Code 2
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
string MACAddress = String.Empty;
foreach (ManagementObject mo in moc)
{
if (MACAddress == String.Empty) // only return MAC Address from first card
{
if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString();
}
mo.Dispose();
}
MACAddress = MACAddress.Replace(":", "");
In first code when we disconnected from network connection then it will return null mac address . second code return the mac address when network adapter connection id disconnected But when we disbled the network connection or remove the IP address of the computer then it will return the null mac address .
How to get the mac address when network connnection disabled, there is no IP address assigned to the PC or network connection disconnected?

When you disable your network adapter, you can't access it at all - it is as if it isn't installed, which is why you don't see a MAC address.
EDIT: Explanation:
A MAC address belongs to a network adapter. If you have 3 adapters you have 3 MAC addresses. If you have no adapters, you have no MAC address.

Related

Pinging an IP and port with C# [duplicate]

I have to check remote IP and Port is available or not.If its is available it will move to next form.If not available it should come to the initial state.I tried using this
while (true)
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
-------
-------
-------
}
I am showing the example coding.it was checking local IP and port and moving to next form.it will check local port and IP is available.if port and IP not available it will come to the initial stage and it was working fine.same thing i have to check in remote Port and IP.
Use the Ping class of .NET to find out if the system is up and connected, the use the PortScanner to check if the port is open. check these links for further reading and exploring.
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping%28v=vs.110%29.aspx
http://social.msdn.microsoft.com/Forums/vstudio/en-US/8e4410bd-307f-4264-9575-cd9882653945/help-with-portscanner-in-c?forum=csharpgeneral
OR
public static bool PingHost(string hostUri, int portNumber)
{
try
{
using (var client = new TcpClient(hostUri, portNumber))
return true;
}
catch (SocketException ex)
{
MessageBox.Show("Error pinging host:'" + hostUri + ":" + portNumber.ToString() + "'");
return false;
}
}

How to get Bluetooth Device Com serial Port in winform C#?

How do I get the port details of the Bluetooth device that I have paired within my windows form c# application?
Manually I can get all port names but I need the com port name that allocated to particular Bluetooth Device.
Check this post
the Win32_PnPEntity is Plug and play devices MSDN
you can go on the drivers also to find your device
// The WMI query
const string QueryString = "SELECT * FROM Win32_PnPSignedDriver ";
SelectQuery WMIquery = new SelectQuery(QueryString);
ManagementObjectSearcher WMIqueryResults = new ManagementObjectSearcher(WMIquery);
// Make sure results were found
if (WMIqueryResults == null)
return;
// Scan query results to find port
ManagementObjectCollection MOC = WMIqueryResults.Get();
foreach (ManagementObject mo in MOC)
{
if (mo["FriendlyName"] != null && mo["FriendlyName"].ToString().Contains("YOUR_DEVICE_NAME"))
{}
//Check the mo Properties to find the COM port
}

How to get IP of computer on lan if you have the computers name, using c#

I'm currently writing a C# program to connect one computer to another on lan.
I have the computer name of the receiving computer but the ip is dynamic so it will change from time to time.
How would I get the lan IP adress of the receiving computer? (the one that goes like 192.168.1.# )
Assuming based on your assumption you are looking for the first IPv4 ip address you can use the following:
String name = "Name";
IPHostEntry ipHostInfo = Dns.GetHostEntry(name);
// OR you can get the name of the current computer using
// IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
// Get the first IPv4 address
IPAddress ip = ipHostInfo.AddressList.Where(n => n.AddressFamily == AddressFamily.InterNetwork).First();
Dns.GetHostAddresses Method
you can resolve Host name to IP as follows
string hostName = "www.Google.com";
IPAddress[] addresslist = Dns.GetHostAddresses(hostName);
foreach (IPAddress address in addresslist)
{
string ip = address.ToString();
}

c# how to get virtual IP assigned to terminal session in Windows 2008R2

I have Windows 2008 R2 server with enabled IP virtualization for Terminal services. I need to know in my program which virtual IP was assigned to session where I run my program.
Now when I get IP address:
String strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] addr = ipEntry.AddressList;
I have only IP of a server not virtual IP assigned to session.
How can I get (using c#) this virtual IP?
Best regards,
Piotr
you may try this
System.Net.IPAddress[] IpAddresses = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName());
for (int i = 0; i < IpAddresses.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, IpAddresses[i].ToString());
}
Use WTSQuerySessionInformation

Setting IP with a c# tool

I'm a c# newby who want to learn more about programming. So I started with a simple tool, wich can set the address of a choosen network adapter to static or dynamic (like the Windows TCP/IP Properties. I set the tool's design exactly like the TCP/IP Properties).
Setting a static IP address to the network adapter works pretty good.
But when I disconnet the Computer form the network and then set the network adapter's IP to dynamic (Obtain an IP address automatically"), it won't set the Windows IP Propertie to dynamic. I'm totaly lost with this problem, I have no idea how to solve it.
I understand that I only get an IP address automatically, when I'm connected to a network (where a router or a DHCP server is enabled).
But when I disconnect the computer form the network, an I set the IP Properties to dynamic with the the Windows TCP/IP Properties, it works well. What is worng in my code?
Thanks a lot for your help!
Below the code I'm using:
public void setDHCPMode()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (!(bool)mo["ipEnabled"])
continue;
try
{
string desc = (string)(mo["Description"]);
if (desc == NICcomboBox.Text)
{
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = null;
ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null);
ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
}
toolStripStatusLabel1.Text = "DHCP set";
}
catch (Exception ex)
{
MessageBox.Show("Unable to set DHCP : " + ex.Message);
}
}
}
I found the problem. It looks like the WMI dosn't work correctly. It's impossible to set the TCP/IP Properties to DHCP, while the cable is unplugged for the specific NIC.
I solved it, through setting DHCP mode in the regestry. Now it works perfectly.

Categories

Resources