我正在尝试打开从我的 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/