C# Help Beginning

bobsanbob

Junior Member
Feb 6, 2009
1
0
0
So I'm teaching myself C# and like to just start learning by doing sort of person and asking questions when I get stuck. I've done some C in the past some I'm familiar with procedural programming a little bit.

So I decided to write an app to retrieve some network information and do some things with it. I'm stuck on getting the subnet mask for my PC and not understanding some this. What I'm guessing is inheritance but I'm just starting to learn OO stuff so not sure.

So C# has a class UnicastIPAddressInformation with a property IPv4Mask that MSDN says gets the IPv4 mask (good!, that's what I want!) and returns an IPAddress object. I'm sure these are pretty easy questions so I apologize but I'm confused why it returns an IPAddress object as opposed to a UnicastIPAddressInformation object and then when I look at the UnicastIPAddressInformation Class it says "You do not create instances of this class; instances are returned in the array returned by the UnicastAddresses property."

Any and all help is greatly appreciated and instead of here's how to do it, I'd appreciate explanation of how to and why. Thanks.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
Look at the UnicastIPAddressInformation class again. Some of it's properties return IPAddress instances that encapsulate the information you want. For example, the Address property returns am IPAddress with the full address in it, and the IPv4Mask property returns an IPAddress with the mask in it. It makes perfect sense that the IPAddress class would be used to represent both the address and the mask, since both are comprised of 4 octets. You're right that you don't create instances of UnicastIPAddressInformation directly. That also makes sense, given that your code cannot create this information, but only read it from the various layers that sit on top of the physical or logical network adapter you're trying to describe. So the correct way to get to this data is to use the IPInterfaceProperties.UnicastAddress property. You also do not create instances of IPInterfaceProperties directly. These are all nested abstract classes. You need to start by first enumerating the NICs in the machine and then work your way in from there. The MSDN page for the NetworkInterface.GetIPProperties method has a complete example:

http://msdn.microsoft.com/en-u...e.getipproperties.aspx
 

Crusty

Lifer
Sep 30, 2001
12,684
2
81
Another way to get your local network settings is to obtain an instance of IPHostEntry from Dns.GetHostEntry(string hostNameOrAddress). The IPHostEntry object has a property called AddressList that is an array of IPAddress objects that represent each NIC you have on the machine(assuming you specify the local machines hostname in Dns.GetHostEntry).