SeedPeers: fix conversion of int representation of IPv4 addresses to InetAddress

Usage of `writeUint32LE()` is wrong on two counts:

* `InetAddress.getByAddress()` expects big-endian values, and the method
  above encodes as little-endian.
* Java int is signed, even if the Java hex literal appears unsigned. The
  above method expects unsigned values.

So we add the previously missing `writeInt32BE()` to ByteUtils and use it.
This commit is contained in:
Andreas Schildbach 2023-03-21 19:10:26 +01:00
parent 72370d0ff6
commit b8f77abe62
2 changed files with 26 additions and 1 deletions

View File

@ -203,6 +203,31 @@ public class ByteUtils {
writeUint32BE(val, ByteBuffer.wrap(out, offset, out.length - offset));
}
/**
* Write 4 bytes to the buffer as signed 32-bit integer in big endian format.
* @param val value to be written
* @param buf buffer to be written into
* @return the buffer
* @throws BufferOverflowException if the value doesn't fit the remaining buffer
*/
public static ByteBuffer writeInt32BE(int val, ByteBuffer buf) throws BufferOverflowException {
return buf.order(ByteOrder.BIG_ENDIAN).putInt((int) val);
}
/**
* Write 4 bytes to the byte array (starting at the offset) as signed 32-bit integer in big endian format.
* @param val value to be written
* @param out buffer to be written into
* @param offset offset into the buffer
* @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or
* if the value doesn't fit the remaining buffer
*/
public static void writeInt32BE(int val, byte[] out, int offset) throws ArrayIndexOutOfBoundsException {
check(offset >= 0 && offset <= out.length - 4, () ->
new ArrayIndexOutOfBoundsException(offset));
writeInt32BE(val, ByteBuffer.wrap(out, offset, out.length - offset));
}
/**
* Write 8 bytes to the buffer as signed 64-bit integer in little endian format.
* @param val value to be written

View File

@ -122,7 +122,7 @@ public class SeedPeers implements PeerDiscovery {
private static InetAddress convertAddress(int seed) throws UnknownHostException {
byte[] v4addr = new byte[4];
ByteUtils.writeUint32LE(seed, v4addr, 0);
ByteUtils.writeInt32BE(seed, v4addr, 0);
return InetAddress.getByAddress(v4addr);
}
}