C++/CLI Code Snippet - Get local computer IP address
C++/CLI code snippet get the IP address from the local machine. For computers with multiple IP addresses with one or more NIC cards can use IP address object list to obtain all the IP addresses.
Bookmark:
C++/CLI Code Snippet - Get local computer IP address
This .Net C++/CLI code snippet get the IP address from the local machine. This function uses System.Net namespace to get local machine hostname and then get a array of IPAddress objects. Modify the exception handling section to meet your project requirements.
04 | System :: String ^GetLocalIP() |
06 | System :: String ^_IP = nullptr ; |
10 | System ::Net::IPHostEntry ^_IPHostEntry = System ::Net::Dns::GetHostEntry( System ::Net::Dns::GetHostName()); |
13 | for each ( System ::Net::IPAddress ^_IPAddress in _IPHostEntry->AddressList) |
17 | if (_IPAddress->AddressFamily. ToString () == "InterNetwork" ) |
19 | _IP = _IPAddress-> ToString (); |
Here is a simple example showing how to use above function (GetLocalIP) to display local machine IP address.
1 | Console :: WriteLine ( "Local computer IP address : " + GetLocalIP()); |
This .Net code snippet gets the array of all the IPAddress objects. Use this method if you are writing sockets applications, a computer can have multiple IP addresses with one or more NIC cards.
04 | array < System ::Net::IPAddress^> ^GetLocalIPList() |
08 | System ::Net::IPHostEntry ^_IPHostEntry = System ::Net::Dns::GetHostEntry( System ::Net::Dns::GetHostName()); |
11 | return _IPHostEntry->AddressList; |
Here is a simple example showing how to use above function (GetLocalIPList) to display all the IP addresses from local machine.
2 | for each ( System ::Net::IPAddress ^_IPAddress in GetLocalIPList()) |
3 | Console :: WriteLine (_IPAddress-> ToString ()); |
7 | for each ( System ::Net::IPAddress ^_IPAddress in GetLocalIPList()) |
8 | Console :: WriteLine (_IPAddress->AddressFamily. ToString () + " = " + _IPAddress-> ToString ()); |
C++/CLI Keywords Used:
- DNS
- IPAddress
- GetHostEntry
- IPHostEntry
- AddressList
- AddressFamily
- InterNetwork
- Exception
Code Snippet Information:
- Applies To: Visual Studio, .Net, C++, CLI, DNS, Domain Name System, IPAddress, GetHostEntry, IPHostEntry, AddressFamily, InterNetwork, Socket programming, Networking, Network monitoring
- Programming Language : C++/CLI
External Resources: