-1

I'm trying to translate a little Python script into Java. It's pretty simple - it sends some data to a UDP port and looks at the result. I'm not a Python guy, and haven't done too much socket programming, but I've figured out the translation of everything except one line:

packet = (b'\x0C\x15\x33\x00' + os.urandom(4) + (b'\x00' * 38) + struct.pack('<H', len(enccmd)) + enccmd).ljust(512, b'\x00')

enccmd is a string containing a command that was encoded previously/

This is building the data packet that's going to be sent. I know that this translates into the creation of a DatagramPacket object, I just don't know how to do it.

Can anyone help?

Sander Smith
  • 1,371
  • 4
  • 20
  • 30

1 Answers1

0

Do you mean sth. like:

 try {
        InetAddress ia;
        ia = InetAddress.getByName("localhost");
        int port = 12345;
        String s = "Hello-World!";
        byte[] data = s.getBytes();
        DatagramPacket packet = new DatagramPacket(data, data.length, ia, port);
        DatagramSocket toSocket = new DatagramSocket();
        toSocket.send(packet);
    } catch (SocketException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnknownHostException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

To build the byte[] you can use:

try {
        ByteArrayOutputStream byte_array_output_stream = new ByteArrayOutputStream();
        DataOutputStream data_output_stream = new DataOutputStream(byte_array_output_stream);
        data_output_stream.writeBytes("\u000c\u0015\u0033\u0000");
        byte[] b = new byte[4];
        new SecureRandom().nextBytes(b);
        data_output_stream.write(b);
        for (int i = 0; i < 38; i++) {
            data_output_stream.writeBytes("\u0000");
        }
        data_output_stream.flush();
        byte[] array = byte_array_output_stream.toByteArray();
        JOptionPane.showMessageDialog(null, Arrays.toString(array));
    } catch (IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
Andie2302
  • 4,825
  • 4
  • 24
  • 43
  • I think he means how does he construct the packet? (his byte array). – demented hedgehog Jan 17 '15 at 03:20
  • Yeah, that's my problem. I know how to ship the data over the socket. I can't figure out how to format the payload. How do you build the DatagramPacket to conform to what the Python code is doing? – Sander Smith Jan 17 '15 at 03:22
  • This is sort of what I need. A few issues: First, don't we want "\0x0c\0x15\0x33\0x00" so we get bytes? Secondly, you've ignored the whole second part of the statement, which is where the really hairy stuff is. How do you do that? – Sander Smith Jan 17 '15 at 13:20