Java UDP无法绑定到本地IP地址(以太网)

时间:2017-10-16 06:48:20

标签: java interface udp ip bind

我的笔记本电脑连接以太网电缆和wifi 我的以太网ip:192.168.18.32 我的wifi ip:192.168.18.167 现在我想通过使用wifi网络接口的java发送udp数据包。 我读到如果我绑定到correspoding ip然后相应的接口将用于发送udp数据包,即如果我绑定到IP 192.168.18.167然后udp数据包将使用wifi接口发送

我的代码是:

  final String wiFiCardAddressName = "192.168.18.32";
  final String ethernetAddressName = "192.168.18.167";
  final InetAddress wiFiCardAddress = InetAddress.getByName(wiFiCardAddressName);
  final InetAddress ethernetAddress = InetAddress.getByName(ethernetAddressName);
  DatagramSocket datagramSocketWifi = new DatagramSocket(10000, wiFiCardAddress);
  System.out.println(ethernetAddress);
  DatagramSocket datagramSocketEt = new DatagramSocket(6666, ethernetAddress);

      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, serverPort);

但每当调用此发送方法时

     datagramSocketWifi.send(sendPacket);
     datagramSocketet.send(sendPacket);

它显示以下错误:

Exception in thread "main" java.net.BindException: Cannot assign requested address: Datagram send failed    
at java.net.DualStackPlainDatagramSocketImpl.socketSend(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.send(Unknown Source)
at java.net.DatagramSocket.send(Unknown Source)
at socket_test.Client_UDP_Bind.main(Client_UDP_Bind.java:50)

1 个答案:

答案 0 :(得分:-1)

当我将服务器移动到外部主机即IP时,我的服务器在localhost上运行,即127.0.0.1,然后这个相同的代码工作。我可以使用ehternet或妻子发送数据包,并可以在wireshark中查看日志。