我需要以以下格式发送UDP数据包:
1 OCTET3 OCTET5 SHORT
例如:
77.125.65.201:27015
十六进制:
4D 7D 41 C9 69 87
这就是我用wireshark捕捉到的:

为什么两个额外的八位数是00,00?
我就是这样格式化的:
byte[] responseHeader = { (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, 0x66, (byte)0x0A };
byte[] testIP = getByteIp("77.125.65.201:27015");
byte[] response = new byte[responseHeader.length + testIP.length];
System.arraycopy(responseHeader, 0, response, 0, responseHeader.length);
System.arraycopy(testIP, 0, response, responseHeader.length, testIP.length);
private byte[] getByteIp(String fullData){
String[] data = fullData.split(":");
byte[] returnArray = new byte[8];
byte[] ip = new byte[4];
try {
ip = InetAddress.getByName(data[0]).getAddress();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] port = new byte[2];
port = ByteBuffer.allocate(4).putInt(Integer.parseInt(data[1])).array();
System.arraycopy(ip, 0, returnArray, 0, ip.length);
System.arraycopy(port, 0, returnArray, ip.length, port.length);
return returnArray;
}发布于 2013-04-28 09:12:11
问题是端口号是一个2字节值,但是您处理的是4字节值。如果你仔细观察,你会发现你有8个字节,而不是6个,两个“重要”字节出现在这些零之后。
无论如何,下面的代码应该做您想要做的事情。
byte[] port = ByteBuffer.allocate(2).putShort(
(short) Integer.parseInt(data[1])).array();https://stackoverflow.com/questions/16261297
复制相似问题