安卓通过名称建立TCP连接

3
我正在尝试从我的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);

        .......
    }

有什么想法吗?
1个回答

0

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

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 文档 中获取代码,并查看它实际标识的名称,然后使用它。


我修改了代码以在我的安卓上运行,但结果是这样的。 - Ian James

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接