成功解决Address is invalid on local machine, or port is not valid on remote machine

解决编写Ftp服务器遇到java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine

问题描述

Socket dataSocket = new Socket(remoteHost,remotePort,InetAddress.getLocalHost(),20);

在学习编写Ftp服务器的时候,上述代码遇到了使用Socket连接20端口时报错,百度网上各种方法都不能解决。包括修改端口号,修改JVM参数,以及在主函数中增加
System.setProperty(“java.net.preferIPv4Stack”, “true”);都无法解决问题

原因所在

经过三天的查找终于找到原因,希望自己以后不会再犯这样的错误。
首先看看InetAddress.getLocalHost()的打印结果

可以看到主机ip为192.168.93.6,在cmd里面用ipconfig查看ip
在这里插入图片描述
问题就出在这里了,InetAddress.getLocalHost()获得的是以太网ip,而我自己使用的是WLAN。所以造成本地机器上的地址无效,修改代码。

Socket dataSocket = new Socket(remoteHost,remotePort,InetAddress.getByName("127.0.0.1"),20);

问题成功解决。

猜你喜欢

转载自blog.csdn.net/qq_43637218/article/details/86086345