Java IPv6 Address String to Bytes - java

How can I convert a String containing the ipv6's machine packet destination to a 16 byte array? I know about getBytes and encodings, but I can't seem to understand which encoding I should use or if I have to convert that String to Hexadecimal or not.
String ipv6 = "2001:0DB8:AC10:FE01:0000:0000:0000:0000";
byte[] bytes = ipv6.getBytes(); //must be a 16 byte array
An example of what I wanna do, just to exemplify.
Obs.: I have to convert the String to a 16 byte array
Thanks

try this
InetAddress a = InetAddress.getByName("2001:0DB8:AC10:FE01:0000:0000:0000:0000");
byte[] bytes = a.getAddress();

The open-source IPAddress Java library will handle a wide range of IPv6addresses, so it can be used if your string need validation or has a wide variety of formats. Disclaimer: I am the project manager of that library.
Example code:
String ipv6 = "::1";
try {
IPAddressString str = new IPAddressString("::1");
IPAddress addr = str.toAddress();
byte[] bytes = addr.getBytes();`
} catch(IPAddressStringException e) {
//e.getMessage has validation error
}

Related

Converting byte array to String Java

I wish to convert a byte array to String but as I do so, my String has 00 before every digit got from the array.
I should have got the following result: 49443a3c3532333437342e313533373936313835323237382e303e
But I have the following:
Please help me, how can I get the nulls away?
I have tried the following ways to convert:
xxxxId is the byteArray
String xxxIdString = new String(Hex.encodeHex(xxxxId));
Thank you!
Try something like this:
String s = new String(bytes);
s = s.replace("\0", "")
It's also posible, that the string will end after the first '\0' received, if thats the case, first iterate through the array and replace '\0' with something like '\n' and do this:
String s = new String(bytes);
s = s.replace("\n", "")
EDIT:
use this for a BYTE-ARRAY:
String s = new String(bytes, StandardCharsets.UTF_8);
use this for a CHAR:
String s = new String(bytes);
Try below code:
byte[] bytes = {...}
String str = new String(bytes, "UTF-8"); // for UTF-8 encoding
please have a look here- How to convert byte array to string and vice versa?
In order to convert Byte array into String format correctly, we have to explicitly create a String object and assign the Byte array to it.
String example = "This is an example";
byte[] bytes = example.getBytes();
String s = new String(bytes);

Json/string/byte conversion operations (sending bytes to socket)

I have a problem with converting JSON object to bytes. I need something like:
aJsonObject = new JSONObject();
// ...put somethin
string msg;
msg = aJsonObject.toString();
count = msg.countBytes(); //calculate how many bytes will string `msg` take
THEN I need to convert count to 2-element byte array (actually I need to send 16bit int to socket), convert msg to count-element byte array, link them together and send to TCP socket.
The most compliacted for me is to make count placed on exactly 16 bits.
Exactly same thing I need to do in reverse. Take 2 bytes, make them int, then read int-bytes from socket and eventually convert them to json.
I will be grateful for any help. Thanks in advance.
A Java String uses UTF-16 encoding. To convert a String to a byte array, simply call the String.getBytes() method, specifying the desired byte encoding, such as UTF-8. Then read the array's length.
aJsonObject = new JSONObject();
// fill JSON as needed...
String msg = aJsonObject.toString();
byte[] bytes = msg.toBytes(StandardCharsets.UTF_8);
int count = bytes.length;
// use length and bytes as needed...
To reverse the process, simply pass the bytes to the String constructor, specifying the same byte encoding:
bytes[] bytes = ...;
String msg = new String(bytes, StandardCharsets.UTF_8);
// use msg as needed...

Java Convert strange string to Burmese language string

Hi my example code is like ;
String ln="á€á€­á€•á€¹á€•á€¶á€”ဲ့";
try {
byte[] b = ln.getBytes("UTF-8");
String s = new String(b, "US-ASCII");
System.out.println(s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
when I run it, it does not print Brumese, Is there a sloution for that ? Thanks
The real problem is that the server is sending back content either with the wrong charset, or double-encoded. If at all possible, you should get that fixed.
In the meantime, you have the right idea—converting the mis-encoded text to the correct charset.
Each character in your String was apparently supposed to be a single byte which was part of an UTF-8 byte sequence. What you're actually seeing is each of those single bytes being treated as a character in the Windows cp1252 charset, and converted to a Java char accordingly.
So, you first want to convert the chars from cp1252 back into the proper bytes:
byte[] b = ln.getBytes("cp1252");
Now you have a true UTF-8 byte sequence, which you can convert into the proper String:
String s = new String(b, StandardCharsets.UTF_8);
// In Java 6, you must use:
//String s = new String(b, "UTF-8");
You should never use US-ASCII if you are decoding, or trying to generate, Burmese characters, or any non-English characters. ASCII consists of codepoints 0 through 127 only.

Converting IPV4 Address from bytes to String

I currently am trying to create a chat server as an assignment and want each message to contain a header. It will contain ipv4 address followed by a letter then a username
I can easily decode string letters from bytes but now I am struggling to decode an ipv4 address from bytes
the representation so far from the bytes is this
[-64, -88, 1, 5]
which in the ipv4 dotted quad format would be 192.168.1.5
I just need a way to try and decode the four bytes of integers to a string or something along those lines
THANKS :D
InetAddress.getByAddress(bytes).getHostAddress()?
That is easily done like this:
byte[] address = ...;
String addressStr = "";
for (int i = 0; i < 4; ++i)
{
int t = 0xFF & address[i];
addressStr += "." + t;
}
addressStr = addressStr.substring(1);

Java TCP Socket receiving bytes with specified length

I am trying to first read 4 bytes(int) specifying the size of the message and then read the remaining bytes based on the byte count. I am using the following code to accomplish this:
DataInputStream dis = new DataInputStream(
mClientSocket.getInputStream());
// read the message length
int len = dis.readInt();
Log.i(TAG, "Reading bytes of length:" + len);
// read the message data
byte[] data = new byte[len];
if (len > 0) {
dis.readFully(data);
} else {
return "";
}
return new String(data);
Is there a better/efficient way of doing this?
From JavaDocs of readUTF:
First, two bytes are read and used to construct an unsigned 16-bit
*integer* in exactly the manner of the readUnsignedShort method . This
integer value is called the UTF length and specifies the number of
additional bytes to be read. These bytes are then converted to
characters by considering them in groups. The length of each group is
computed from the value of the first byte of the group. The byte
following a group, if any, is the first byte of the next group.
The only problem with this is that your protocol seems to only send 4 bytes for the payload length. Perhaps you can do a similar method but increase the size of length sentinel read to 4 bytes/32-bits.
Also, I see that you are just doing new String(bytes) which works fine as long as the encoding of the data is the same as "the platform's default charset." See javadoc So it would be much safer to just ensure that you are encoding it correctly(e.g. if you know that the sender sends it as UTF-8 then do new String(bytes,"UTF-8") instead).
How about
DataInputStream dis = new DataInputStream(new BufferedInputStream(
mClientSocket.getInputStream()));
return dis.readUTF();
You can use read(byte[] b, int off, int len) like this
byte[] data = new byte[len];
dis.read(data,0,len);

Categories