You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# DNS类在Android Java中的等效实现:获取IP地址

Replicating C# DNS IP Address Retrieval in Android Java

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#'s IPAddress and Dns functionality. It encapsulates both host names and IP addresses.
    • getLocalHost(): Fetches the local host's InetAddress instance, which includes the host name (just like Dns.GetHostName() in C#).
    • getAllByName(String hostName): Resolves the given host name into an array of InetAddress objects, matching the AddressList property from C#'s IPHostEntry.
    • getHostAddress(): Extracts the string representation of the IP address from an InetAddress instance, similar to accessing an IPAddress object's ToString() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:38:53