Java为什么不是在构造函数中指定的本地端口上侦听的套接字/绑定到?

时间:2014-07-24 13:25:51

标签: java sockets network-programming udp

我有一个奇怪的问题,让我们考虑以下代码:

import java.net.*;
import java.util.Enumeration;

public class Main{

   public static void main(String args[]) throws Exception   {
      Inet4Address myIp = (Inet4Address)Inet4Address.getByName(Main.getLanIp());
      InetSocketAddress myAddr = new InetSocketAddress(myIp, LocalportNumber);
      if(myIp == null){
          throw new Exception();
      }
      DatagramSocket socket = new DatagramSocket(myAddr);
      socket.setReuseAddress(true);
      InetAddress IPAddress = InetAddress.getByName("239.xxx.xxx.xxx");
      byte[] sendData = new byte[1024];
      byte[] receiveData = new byte[1024];
      String sentence = "PAYLOAD";
      sendData = sentence.getBytes();
      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, distantPortNumber);
      DatagramPacket receivePacket = new DatagramPacket(receiveData, 1024);
      socket.send(sendPacket);
      System.out.println("Packet sent");
      socket.receive(receivePacket);
      String modifiedSentence = new String(receivePacket.getData());
      System.out.println("FROM SERVER:" + modifiedSentence);
      socket.close();
   }

   static public String getLanIp() throws SocketException{
        InetAddress inet_addr = null;
        NetworkInterface cur = null;

        for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();){
            cur = interfaces.nextElement();
            try {
                if (cur.isLoopback())
                {
                    continue;
                }
            } catch (SocketException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("interface " + cur.getName());

            for (InterfaceAddress addr : cur.getInterfaceAddresses()){

                inet_addr = addr.getAddress();

                if ( !( inet_addr instanceof Inet4Address)){
                    continue;
                }

                System.out.println("  address: " + inet_addr.getHostAddress() + "/" + addr.getNetworkPrefixLength());
                System.out.println("  broadcast address: " + addr.getBroadcast().getHostAddress());
            }
        }
        return inet_addr.getHostAddress();
    }
}

执行追踪: &#34;&#34;&#34; 接口eth0   地址:192.168.0.20/24   广播地址:192.168.0.255 包发送 &#34;&#34;&#34;

当我运行前面的代码时,会发送一个数据包,服务器应答,但我仍然阻止接收方法,我可以看到wireshark上的传入数据包到达我的计算机。但是当我尝试:&#34; netstat -npl&#34;时,我看到一个java进程在端口localPort上侦听。我试过了一个&#34; nc -vvv -u 9393&#34;来自远程(lan),然后输入随机句子......什么都没发生。我在本地(使用我的外部IP,我的环回IP)尝试了同样的问题。是否存在可能阻止内核与jvm之间收到的udp数据包的已知问题列表?

1 个答案:

答案 0 :(得分:0)

我发现了我的问题:我的iptable防火墙......我阻止了所有传入的流量,这不是我的传出流量的答案。这就是为什么我看到wireshark上的流量,但我没有到达Java套接字......

所以解决办法是打开我的防火墙-_-“