org.bdware.dogp.codec.InetAddressUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of doip-audit-tool Show documentation
Show all versions of doip-audit-tool Show documentation
doip audit tool developed by bdware
The newest version!
package org.bdware.dogp.codec;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
public class InetAddressUtil {
public static byte[] convertInetSocketAddressToBytes(InetSocketAddress address) {
byte[] ipAndPort = new byte[6];
int port = address.getPort();
System.arraycopy(address.getAddress().getAddress(), 0, ipAndPort, 0, 4);
ipAndPort[4] = (byte) ((port & 0xff00) >> 8);
ipAndPort[5] = (byte) (port & 0xff);
return ipAndPort;
}
public static InetSocketAddress convertBytesToInetSocketAddress(byte[] bytes) {
byte[] address = new byte[4];
System.arraycopy(bytes, 0, address, 0, 4);
try {
InetAddress dstAddress = InetAddress.getByAddress(address);
int dstPort = ((bytes[4] << 8) + bytes[5]) & 0xffff;
return new InetSocketAddress(dstAddress, dstPort);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public static byte[] convertIpPortToBytes(String ip, int port) {
byte[] ipAndPort = new byte[6];
String[] splited = ip.split("\\.");
assert splited.length == 4;
for (int i = 0; i < splited.length; i++) {
int val = Integer.valueOf(splited[i]);
ipAndPort[i] = (byte) (val & 0xff);
}
ipAndPort[4] = (byte) ((port & 0xff00) >> 8);
ipAndPort[5] = (byte) (port & 0xff);
return ipAndPort;
}
public static boolean notEmpty(byte[] data) {
if (data != null) {
for (byte b : data) {
if (b != 0) return true;
}
}
return false;
}
}