使用Java发送和接收UDP数据包?

时间:2012-05-11 18:37:35

标签: java udp firewall

我制作了一个程序,从客户端向服务器发送UDP数据包,这里是发送器代码

import java.io.IOException;
import java.net.*;

/**
 *
 * @author hp
 */
public class JavaApplication9 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws UnknownHostException, SocketException, IOException  {
        // TODO code application logic here
        byte[] buffer = {10,23,12,31,43,32,24};
        byte [] IP={-64,-88,1,106};
        InetAddress address = InetAddress.getByAddress(IP);
        DatagramPacket packet = new DatagramPacket(
                buffer, buffer.length, address, 57
                );
        DatagramSocket datagramSocket = new DatagramSocket();
        datagramSocket.send(packet);
        System.out.println(InetAddress.getLocalHost().getHostAddress());


    }
}

接收者代码功能

public void run(){

    try{
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        byte[] sendData = new byte[8];

        while(true)
           {
              DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData());
              System.out.println("RECEIVED: " + sentence);
              InetAddress IPAddress = receivePacket.getAddress();
              String sendString = "polo";
              sendData = sendString.getBytes();
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
              serverSocket.send(sendPacket);
           }
    }catch (Exception e){
    }
}

我使用过WireShark程序。 UDP数据包是在接收器的WireShark程序中接收的,但Java程序无法识别它,程序只是一直在监听端口而没有任何反应?

1 个答案:

答案 0 :(得分:30)

接收方必须设置接收方端口以匹配发送方DatagramPacket中设置的端口。对于调试尝试侦听端口> 1024(例如8000或9000)。端口< 1024通常由系统服务使用,需要管理员访问才能在这样的端口上绑定。

如果接收方将数据包发送到它正在侦听的硬编码端口(例如端口57),并且发送方位于同一台机器上,那么您将创建一个到接收方本身的环回。始终使用数据包中指定的端口,如果是生产软件,则无论如何都需要检查以防止出现这种情况。

数据包无法到达目的地的另一个原因是发件人中指定的IP地址错误。与TCP不同的UDP将尝试发送数据包,即使地址无法访问且发送方也不会收到错误指示。您可以通过在接收器中打印地址来检查这一点,作为调试的预防措施。

在您设置的发件人中:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

但是以字符串形式使用地址可能更简单:

 InetAddress address = InetAddress.getByName("192.168.1.106");

换句话说,您将target设置为192.168.1.106。如果这不是接收者,那么你将无法获得该数据包。

这是一个简单的UDP接收器:

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              InetAddress IPAddress = receivePacket.getAddress();
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   IPAddress, receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}