Converting IPV4 Address from bytes to String
Asked Answered
D

2

5

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

Distilled answered 15/9, 2013 at 0:17 Comment(0)
P
12

InetAddress.getByAddress(bytes).getHostAddress()?

Polyurethane answered 15/9, 2013 at 0:20 Comment(0)
C
0

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);
Conchita answered 15/9, 2013 at 0:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.