how to retrieve IP v6 subnet mask length - c#

I'm coding an application that has to get the network adapters configuration on a Windows 7 machine just like it's done in the Windows network adapters configuration panel:
So far I can get pretty much all the information I need from NetworkInterface.GetAllNetworkInterfaces() EXCEPT the subnet prefix length.
I'm aware that it can be retrieved from the C++ struc PMIB_UNICASTIPADDRESS_TABLE via OnLinkPrefixLength but I'm trying to stay in .net.
I also took a look at the Win32_NetworkAdapterConfiguration WMI class but it only seems to return the IP v4 subnet mask.
I also know that some information (not the prefix length, as far as I know) are in the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters\Interfaces\{CLSID}
I also used SysInternals ProcessMon to try to get anything usefull when saving the network adapter settings but found nothing...
So, is there any clean .NET way to get this value? (getting it from the registry wouldn't be a problem)
EDIT: Gateways
This doesn't concern the actual question, but for those who need to retrieve the entire network adapter IPv6 configuration, the IPInterfaceProperties.GatewayAdresses property only supports the IPv4 gateways. As mentionned in the answer comments below, the only way to get the entire info until .NET framework 4.5 is to call WMI.

You can do so using Win32_NetworkAdapterConfiguration. You might have overlooked it.
IPSubnet will return an array of strings. Use the second value.
I didn't have time to whip up some C# code, but I'm sure you can handle it. Using WBEMTEST, I pulled this:
instance of Win32_NetworkAdapterConfiguration
{
Caption = "[00000010] Intel(R) 82579V Gigabit Network Connection";
DatabasePath = "%SystemRoot%\\System32\\drivers\\etc";
DefaultIPGateway = {"192.168.1.1"};
Description = "Intel(R) 82579V Gigabit Network Connection";
DHCPEnabled = TRUE;
DHCPLeaseExpires = "20120808052416.000000-240";
DHCPLeaseObtained = "20120807052416.000000-240";
DHCPServer = "192.168.1.1";
DNSDomainSuffixSearchOrder = {"*REDACTED*"};
DNSEnabledForWINSResolution = FALSE;
DNSHostName = "*REDACTED*";
DNSServerSearchOrder = {"192.168.1.1"};
DomainDNSRegistrationEnabled = FALSE;
FullDNSRegistrationEnabled = TRUE;
GatewayCostMetric = {0};
Index = 10;
InterfaceIndex = 12;
IPAddress = {"192.168.1.100", "fe80::d53e:b369:629a:7f95"};
IPConnectionMetric = 10;
IPEnabled = TRUE;
IPFilterSecurityEnabled = FALSE;
IPSecPermitIPProtocols = {};
IPSecPermitTCPPorts = {};
IPSecPermitUDPPorts = {};
IPSubnet = {"255.255.255.0", "64"};
MACAddress = "*REDACTED*";
ServiceName = "e1iexpress";
SettingID = "{B102679F-36AD-4D80-9D3B-D18C7B8FBF24}";
TcpipNetbiosOptions = 0;
WINSEnableLMHostsLookup = TRUE;
WINSScopeID = "";
};
IPSubnet[1] = IPv6 subnet;
Edit: Here's some code.
StringBuilder sBuilder = new StringBuilder();
ManagementObjectCollection objects = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration").Get();
foreach (ManagementObject mObject in objects)
{
string description = (string)mObject["Description"];
string[] addresses = (string[])mObject["IPAddress"];
string[] subnets = (string[])mObject["IPSubnet"];
if (addresses == null && subnets == null)
continue;
sBuilder.AppendLine(description);
sBuilder.AppendLine(string.Empty.PadRight(description.Length,'-'));
if (addresses != null)
{
sBuilder.Append("IPv4 Address: ");
sBuilder.AppendLine(addresses[0]);
if (addresses.Length > 1)
{
sBuilder.Append("IPv6 Address: ");
sBuilder.AppendLine(addresses[1]);
}
}
if (subnets != null)
{
sBuilder.Append("IPv4 Subnet: ");
sBuilder.AppendLine(subnets[0]);
if (subnets.Length > 1)
{
sBuilder.Append("IPv6 Subnet: ");
sBuilder.AppendLine(subnets[1]);
}
}
sBuilder.AppendLine();
sBuilder.AppendLine();
}
string output = sBuilder.ToString().Trim();
MessageBox.Show(output);
and some output:
Intel(R) 82579V Gigabit Network Connection
------------------------------------------
IPv4 Address: 192.168.1.100
IPv6 Address: fe80::d53e:b369:629a:7f95
IPv4 Subnet: 255.255.255.0
IPv6 Subnet: 64
Edit: I'm just going to clarify in case somebody searches for this later. The second item isn't always the IPv6 value. IPv4 can have multiple addresses and subnets. Use Integer.TryParse on the IPSubnet array value to make sure it's an IPv6 subnet and/or use the last item.

Parse the input stream of netsh with arguments:
interface ipv6 show route
Hope this helps!

Related

how to get device IP in WP 8.1? [duplicate]

This question already has answers here:
IP address in windows phone 8
(3 answers)
Closed 8 years ago.
I just need to get the current IP of the device within the local network.
Something like...
var IP = IPInformation.GetIP();
Sorry for this easy question... just can't find something.
You need to use the GetHostNames() method through NetworkInformation class (Windows.Networking.Connectivity.NetworkInformation).
You will retrieve an HostName objects Collection which contain all IP addresses (in DisplayName property)
List<string> ipAddresses = new List<string>();
var hostnames = NetworkInformation.GetHostNames();
foreach (var hn in hostnames)
{
//IanaInterfaceType == 71 => Wifi
//IanaInterfaceType == 6 => Ethernet (Emulator)
if (hn.IPInformation != null &&
(hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71
|| hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
{
string ipAddress = hn.DisplayName;
ipAddresses.Add(ipAddress);
}
}
Source
The IPAddresses method obtains the selected server IP address information.
It then displays the type of address family supported by the server and its
IP address in standard and byte format.
private static void IPAddresses(string server)
{
try
{
System.Text.ASCIIEncoding ASCII = new System.Text.ASCIIEncoding();
// Get server related information.
IPHostEntry heserver = Dns.GetHostEntry(server);
// Loop on the AddressList
foreach (IPAddress curAdd in heserver.AddressList)
{
// Display the type of address family supported by the server. If the
// server is IPv6-enabled this value is: InternNetworkV6. If the server
// is also IPv4-enabled there will be an additional value of InterNetwork.
Console.WriteLine("AddressFamily: " + curAdd.AddressFamily.ToString());
// Display the ScopeId property in case of IPV6 addresses.
if(curAdd.AddressFamily.ToString() == ProtocolFamily.InterNetworkV6.ToString())
Console.WriteLine("Scope Id: " + curAdd.ScopeId.ToString());
// Display the server IP address in the standard format. In
// IPv4 the format will be dotted-quad notation, in IPv6 it will be
// in in colon-hexadecimal notation.
Console.WriteLine("Address: " + curAdd.ToString());
// Display the server IP address in byte format.
Console.Write("AddressBytes: ");
Byte[] bytes = curAdd.GetAddressBytes();
for (int i = 0; i < bytes.Length; i++)
{
Console.Write(bytes[i]);
}
Console.WriteLine("\r\n");
}
}

How to get a mac address

Can I get a MAC address that are connected to my site.
this code get mac address host and return error permission.
String macadress = string.Empty;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
OperationalStatus ot = nic.OperationalStatus;
if (nic.OperationalStatus == OperationalStatus.Up)
{
macadress = nic.GetPhysicalAddress().ToString();
break;
}
}
return macadress;
now how can get mac address users???
2.
how can get ip users???
Unfortunately you can't get the user's MAC address in the way that you want. It's my understanding that MAC addresses are stripped from packets when they leave your local network.
You can try to get the user's address from Request.UserHostAddress. However if you are behind a load balancer or content distribution network then you might want to try looking in Request.Headers["X-Forwarded-For"] first - this is where the users original IP address will often be written when the request is forwarded on by something.
The approach I'll usually take is to try something along the lines of:
var address = Request.Headers["X-Forwarded-For"];
if (String.IsNullOrEmpty(address))
address = Request.UserHostAddress;
The last project I worked on, we actually logged both, in case the forwarded for header had been faked.
You cannot get the MAC address from the request, however, you can get the IP with Request.UserHostAddress
You cannot get the MAC address of the end-user's machine.
You can get the user's public IP address using Request.UserHostAddress.
Note the IP address this will not be unique per-user.
If multiple users are behind the same proxy or are on a corporate network, they will usually share the same address.
You can check the X-Forwarded-For header to get a little more information.
Note that this header can be chained or faked.
public string GetMacAddress(string ipAddress)
{
string macAddress = string.Empty;
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
pProcess.StartInfo.FileName = "arp";
pProcess.StartInfo.Arguments = "-a " + ipAddress;
pProcess.StartInfo.UseShellExecute = false;
pProcess.StartInfo.RedirectStandardOutput = true;
pProcess.StartInfo.CreateNoWindow = true;
pProcess.Start();
string strOutput = pProcess.StandardOutput.ReadToEnd();
string[] substrings = strOutput.Split('-');
if (substrings.Length >= 8)
{
macAddress = substrings[3].Substring(Math.Max(0, substrings[3].Length - 2)) + "-" + substrings[4] + "-" + substrings[5] + "-" + substrings[6] + "-" + substrings[7] + "-" +
substrings[8].Substring(0, 2);
return macAddress;
}
else
{
return "not found";
}
}

Any way to turn the "internet off" in windows using c#?

I am looking for pointers towards APIs in c# that will allow me to control my Internet connection by turning the connection on and off.
I want to write a little console app that will allow me to turn my access on and off , allowing for productivity to skyrocket :) (as well as learning something in the process)
Thanks !!
If you're using Windows Vista you can use the built-in firewall to block any internet access.
The following code creates a firewall rule that blocks any outgoing connections on all of your network adapters:
using NetFwTypeLib; // Located in FirewallAPI.dll
...
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Description = "Used to block all internet access.";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = "Block Internet";
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(firewallRule);
Then remove the rule when you want to allow internet access again:
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Remove("Block Internet");
This is a slight modification of some other code that I’ve used, so I can’t make any guarantees that it’ll work. Once again, keep in mind that you'll need Windows Vista (or later) and administrative privileges for this to work.
Link to the firewall API documentation.
This is what I am currently using (my idea, not an api):
System.Diagnostics;
void InternetConnection(string str)
{
ProcessStartInfo internet = new ProcessStartInfo()
{
FileName = "cmd.exe",
Arguments = "/C ipconfig /" + str,
WindowStyle = ProcessWindowStyle.Hidden
};
Process.Start(internet);
}
Disconnect from internet: InternetConnection("release");
Connect to internet: InternetConnection("renew");
Disconnecting will just remove the access to internet (it will show a caution icon in the wifi icon).
Connecting might take five seconds or more.
Out of topic:
In any cases you might want to check if you're connected or not (when you use the code above), I better suggest this:
System.Net.NetworkInformation;
public static bool CheckInternetConnection()
{
try
{
Ping myPing = new Ping();
String host = "google.com";
byte[] buffer = new byte[32];
int timeout = 1000;
PingOptions pingOptions = new PingOptions();
PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
return (reply.Status == IPStatus.Success);
}
catch (Exception)
{
return false;
}
}
There are actually a myriad of ways to turn off (Read: break) your internet access, but I think the simplest one would be to turn of the network interface that connects you to the internet.
Here is a link to get you started:
Identifying active network interface
Here's a sample program that does it using WMI management objects.
In the example, I'm targeting my wireless adapter by looking for network adapters that have "Wireless" in their name. You could figure out some substring that identifies the name of the adapter that you are targeting (you can get the names by doing ipconfig /all at a command line). Not passing a substring would cause this to go through all adapters, which is kinda severe. You'll need to add a reference to System.Management to your project.
using System;
using System.Management;
namespace ConsoleAdapterEnabler
{
public static class NetworkAdapterEnabler
{
public static ManagementObjectSearcher GetWMINetworkAdapters(String filterExpression = "")
{
String queryString = "SELECT * FROM Win32_NetworkAdapter";
if (filterExpression.Length > 0)
{
queryString += String.Format(" WHERE Name LIKE '%{0}%' ", filterExpression);
}
WqlObjectQuery query = new WqlObjectQuery(queryString);
ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(query);
return objectSearcher;
}
public static void EnableWMINetworkAdapters(String filterExpression = "")
{
foreach (ManagementObject adapter in GetWMINetworkAdapters(filterExpression).Get())
{
//only enable if not already enabled
if (((bool)adapter.Properties["NetEnabled"].Value) != true)
{
adapter.InvokeMethod("Enable", null);
}
}
}
public static void DisableWMINetworkAdapters(String filterExpression = "")
{
foreach (ManagementObject adapter in GetWMINetworkAdapters(filterExpression).Get())
{
//If enabled, then disable
if (((bool)adapter.Properties["NetEnabled"].Value)==true)
{
adapter.InvokeMethod("Disable", null);
}
}
}
}
class Program
{
public static int Main(string[] args)
{
NetworkAdapterEnabler.DisableWMINetworkAdapters("Wireless");
Console.WriteLine("Press any key to continue");
var key = Console.ReadKey();
NetworkAdapterEnabler.EnableWMINetworkAdapters("Wireless");
Console.WriteLine("Press any key to continue");
key = Console.ReadKey();
return 0;
}
}
}
public static void BlockingOfData()
{
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.set_DefaultOutboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN, NET_FW_ACTION_.NET_FW_ACTION_BLOCK);
firewallPolicy.set_DefaultOutboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE, NET_FW_ACTION_.NET_FW_ACTION_BLOCK);
firewallPolicy.set_DefaultOutboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC, NET_FW_ACTION_.NET_FW_ACTION_BLOCK);
}

Get the list of all SSIDs and their mac address

Is there a way to get a list of all SSID's and their mac address of reachable signals in my area?
I tried the Nativ WlanApi in my c# code. What I get is the list of all ssid's, but for
getting their mac address, I don't have any idea.
This is the code I using for getting the list:
private void show_all_ssids_Click(object sender, EventArgs e)
{
WlanClient client = new WlanClient();
foreach ( WlanClient.WlanInterface wlanIface in client.Interfaces )
{
// Lists all available networks
Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList( 0 );
this.ssidList.Text = "";
foreach ( Wlan.WlanAvailableNetwork network in networks )
{
//Trace.WriteLine( GetStringForSSID(network.dot11Ssid));
this.ssidList.Text += GetStringForSSID(network.dot11Ssid) + "\r\n";
}
}
}
static string GetStringForSSID(Wlan.Dot11Ssid ssid)
{
return Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
}
I hope there is a way.
In order to get a MAC address you would need to connect to that wireless network. Once you are connected you should be able to get the MAC address of machines on the immediate network using the same methods that you might for traditional wired networks - I believe that the best way of doing that would be by parsing the output of the arp -a command.
this is the solution:
Dim networksBss As Wlan.WlanBssEntry() = SelectedWifiAdapter.GetNetworkBssList()
For car = 0 To networksBss(i).dot11Bssid.Length - 1
If Len(Hex(networksBss(i).dot11Bssid(car))) = 1 Then ThisScan(i).MAC = ThisScan(i).MAC & "0"
ThisScan(i).MAC = ThisScan(i).MAC & Hex(networksBss(i).dot11Bssid(car)) & ":"
Next
anyway i'm still looking for a way to find details (strenght) of networks with SSID="" associating it with the proper MAC.

How to find a list of wireless networks (SSID's) in Java, C#, and/or C?

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.

Categories