按名称的android tcp连接

标签 android networking tcp connection hostname

我正在尝试打开从我的 Android 应用程序到运行在 Roving Networks WiFly 上的服务器的 TCP 连接。 WiFly 在我的路由器上显示为主机名 WiFly,IP 地址为 192.168.1.4

当我使用 ip 地址连接时,连接会正确打开,但如果我使用主机名连接,则会出现错误:

无法打开主机“wifly”:没有与主机名关联的地址

这里是使用的代码 fragment :

    try 
    {
        InetAddress serverAddr = InetAddress.getByName("wifly");

        Log.d("TCP Client", "C: Connecting...");

        //create a socket to make the connection with the server
        Socket socket = new Socket(serverAddr, SERVERPORT);

        .......
    }

有什么想法吗?

最佳答案

你应该检查名字是否正确 您可以使用

列出所有主机
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
        out.printf("\n");
     }
}  

代码取自 Oracle documentation

并查看它标识的实际名称,然后使用它。

关于按名称的android tcp连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13045158/

相关文章:

html - 在网页读取之前更改 IP 地址

android - 如何使用 MediaPlayer 或 SoundPool 在 android 中处理速度和音调

Android 使用 Key 将 JSONObject 添加到 JSONArray

android - 无法从 MediaStore 中删除

java - 处理网络(URL、连接等)时要捕获哪些未经检查的异常?

go - 在 golang 中通过 TCP 套接字发送数百万条短消息

java - 使用 setImageResource 的相对路径

Java - 端口监听程序的漏洞是什么?

networking - Docker:将日志发送到本地主机不起作用,但 0.0.0.0 可以工作,为什么?

python-3.x - 使用 VB.Net 通过 TCP 发送文件并使用 Python3.6 中的 Socket 接收时出现文件编码错误