C# DNS类在Android Java中的等效实现:获取IP地址
Hey there! Let's break down how to translate that C# DNS functionality into Android Java. The core equivalent here uses Java's built-in InetAddress class, which handles host name resolution and IP address management—perfect for replacing C#'s Dns and IPAddress logic.
Step-by-Step Implementation
First, here's the direct Java equivalent to your C# code:
import java.net.InetAddress; import java.net.UnknownHostException; import android.util.Log; // Inside your activity or utility method try { // Get the local host name (matches C#'s Dns.GetHostName()) String localHostName = InetAddress.getLocalHost().getHostName(); // Retrieve all IP addresses associated with the host name (matches Dns.GetHostEntry().AddressList) InetAddress[] ipAddresses = InetAddress.getAllByName(localHostName); // Iterate through the IP addresses (just like accessing AddressList in C#) for (InetAddress addr : ipAddresses) { String ip = addr.getHostAddress(); Log.d("LOCAL_IP", "Found IP: " + ip); } } catch (UnknownHostException e) { // Handle cases where the host name can't be resolved Log.e("DNS_ERROR", "Failed to resolve host name", e); }
Key Classes & Methods Explained
InetAddress: This is the primary class you'll use—it's Java's equivalent to combining C#'sIPAddressandDnsfunctionality. It encapsulates both host names and IP addresses.getLocalHost(): Fetches the local host'sInetAddressinstance, which includes the host name (just likeDns.GetHostName()in C#).getAllByName(String hostName): Resolves the given host name into an array ofInetAddressobjects, matching theAddressListproperty from C#'sIPHostEntry.getHostAddress(): Extracts the string representation of the IP address from anInetAddressinstance, similar to accessing anIPAddressobject'sToString()method in C#.
Important Android Notes
Don't forget to add the necessary permissions to your AndroidManifest.xml—Android requires network permissions to perform DNS lookups:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Also, keep in mind that on newer Android versions (API 28+), you might need to handle network operations off the main thread to avoid NetworkOnMainThreadException—consider using a coroutine, AsyncTask, or background thread for this logic.
内容的提问来源于stack exchange,提问作者Vojtěch Prchal

