【问题标题】:android tcp connection by nameandroid tcp 连接名称
【发布时间】:2023-03-05 07:37:02
【问题描述】:

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

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

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

这是使用的代码片段:

    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);

        .......
    }

有什么想法吗?

【问题讨论】:

    标签: android networking tcp connection hostname


    【解决方案1】:

    您应该检查名称是否正确 您可以使用列出所有主机

    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 上运行,但结果是这样的
    猜你喜欢
    • 2011-10-06
    • 2015-03-20
    • 1970-01-01
    • 2014-01-22
    • 2014-01-13
    • 2018-02-05
    • 2020-03-17
    • 2012-12-06
    • 2012-10-10
    相关资源
    最近更新 更多