简体   繁体   中英

Received UDP message has incorrect length

I am recieving a UDP message from a DatagramSocket and am trying to parse the message like this:

this.broadSock.receive(recvPacket);

// Decode response
byte[] response = recvPacket.getData();
String strResp = new String(response);
String[] splitResp = strResp.split("\\s+");
log.debug("The String: " + strResp + " has the length " + strResp.length());

InetAddress lobbyAdress = InetAddress.getByName(splitResp[0].substring(1));
String portStr = splitResp[1];
int lobbyPort = Integer.parseInt(portStr);

I am getting the following Exception:

java.lang.NumberFormatException: For input string: "8080"

So there is something wrong with the received String as the debug output gives me:

The String: /192.168.0.11 8080 has the length 256

Anybody an idea why this is happening?

The length is provided, and you're ignoring it. It should be:

String strResp = new String(packet.getData(), packet.getOffset(), packet.getLength());
String[] splitResp = strResp.split("\\s+");
log.debug("The response: " + strResp + " has the length " + packet.length());

The fact that strResp.length is 256 is a symptom of a bug in your code. It should be 18 instead.

You are constructing strResp using the entire length of the DatagramPacket buffer without regard to how many bytes are actually in that buffer. DatagramPacket.getData() does not return a new byte[] for just the bytes received. It returns the entire buffer.

That means strResp ends up with 238 extra characters after the port number, and they are not whitespace characters that would be stripped off by split("\\\\s+") , so splitResp[1] , and thus strPort , ends up with more than just digit characters in it, thus violating the requirements of Integer.parseInt() .

You need to take the DatagramPacket length into account when constructing strResp :

byte[] response = recvPacket.getData();
int responseOffset = recvPacket.getOffset();
int responseLength = recvPacket.getLength();
String strResp = new String(response, responseOffset, responseLength);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM