JAVA /连接超时与套接字绑定

时间:2019-02-25 16:03:54

标签: java sockets interface binding

两个部分:

  InetAddress ia = Inet4Address.getByAddress(new byte[]{(byte)192,(byte)168,(byte)10,(byte)100});
  Socket socket = new Socket();
  InetSocketAddress isa = new InetSocketAddress("82.146.58.81", 5277);
  socket.bind(new InetSocketAddress(ia, 0));
  System.out.println("local_address:" + socket.getLocalSocketAddress());
  socket.connect(isa, 1000);
  Thread.sleep(1000);
  socket.close();
  System.out.println("done_1");

  InetAddress ia_2 = Inet4Address.getByAddress(new byte[]{(byte)172,(byte)20,(byte)10,(byte)2});
  Socket socket_2 = new Socket();
  InetSocketAddress isa2 = new InetSocketAddress("82.146.58.81", 5277);
  socket_2.bind(new InetSocketAddress(ia_2, 0));
  System.out.println("local_address:" + socket_2.getLocalSocketAddress());
  socket_2.connect(isa2, 30000);
  Thread.sleep(1000);
  socket_2.close();
  System.out.println("done_2");

代码的第一部分有效,第二部分无效-java.net.SocketTimeoutException:连接超时。 我正在尝试通过不同的接口与主机“ 82.146.58.81”进行通信。 但是只有具有默认路由的部分才能成功。为什么?

更新:我在Ubuntu 17.10上工作,在Armbian中似乎也有同样的问题。 Windows7下无法再现的问题

更新:错误的OUT接口: [12979.049742] IN = OUT = enp4s0 SRC = 172.20.10.2 DST = 82.146.58.81 LEN = 60 TOS = 0x00 PREC = 0x00 TTL = 64 ID = 25967 DF PROTO = TCP SPT = 48985 DPT = 5277 WINDOW = 29200 RES = 0x00 SYN URGP = 0

kostas@work:~$ ifconfig 
enp0s16f0u1c4i2: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.20.10.2  netmask 255.255.255.240  broadcast 172.20.10.15
        inet6 fe80::17c7:4582:897b:11d5  prefixlen 64  scopeid 0x20<link>
        ether 86:38:35:c8:f5:39  txqueuelen 1000  (Ethernet)
        RX packets 575  bytes 117085 (117.0 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 686  bytes 82681 (82.6 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

enp4s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.10.100  netmask 255.255.255.0  broadcast 192.168.10.255
        inet6 fe80::80b9:8cf3:92c6:4aef  prefixlen 64  scopeid 0x20<link>
        ether 00:e0:66:ae:2a:de  txqueuelen 1000  (Ethernet)
        RX packets 100455  bytes 65543315 (65.5 MB)
        RX errors 0  dropped 1  overruns 0  frame 0
        TX packets 75513  bytes 15658830 (15.6 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

kostas@work:~$ route
Таблица маршутизации ядра протокола IP
Destination Gateway Genmask Flags Metric Ref Use Iface
default         unknown         0.0.0.0         UG    100    0        0 enp4s0
default         gateway         0.0.0.0         UG    101    0        0 enp0s16f0u1c4i2


kostas@work:~$ ping mail.ru -I enp0s16f0u1c4i2
PING mail.ru (217.69.139.202) from 172.20.10.2 enp0s16f0u1c4i2: 56(84) bytes of data.
64 bytes from mail.ru (217.69.139.202): icmp_seq=1 ttl=51 time=508 ms
64 bytes from mail.ru (217.69.139.202): icmp_seq=2 ttl=51 time=187 ms

1 个答案:

答案 0 :(得分:0)

“但是,许多操作系统不遵循此“提示”,并且仍将使用路由表。”

Answer here