Alachisoft.NCache.Common.Net.Address Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of nc-common Show documentation
Show all versions of nc-common Show documentation
Internal package of Alachisoft.
package Alachisoft.NCache.Common.Net;
import com.alachisoft.ncache.serialization.core.io.ICompactSerializable;
import com.alachisoft.ncache.serialization.core.io.NCacheObjectInput;
import com.alachisoft.ncache.serialization.core.io.NCacheObjectOutput;
import com.alachisoft.ncache.serialization.standard.io.CompactReader;
import com.alachisoft.ncache.serialization.standard.io.CompactWriter;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
//C# TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java:
//#if !EXPRESS || (EXPRESS && PROFESSIONAL)
//#else
//#endif
/**
* Abstract address. Used to identify members on a group to send messages to. Addresses are mostly generated by the bottom-most (transport) layers (e.g. UDP, TCP, LOOPBACK).
* Subclasses need to implement the following methods: - isMultiCastAddress()
- equals()
- hashCode()
- compareTo()
*
*
Bela Ban
*/
public class Address implements Cloneable, java.lang.Comparable, ICompactSerializable, Serializable {
public static boolean resolve_dns = false;
private InetAddress ip_addr;
private int port;
private byte[] additional_data;
public Address() {
}
public Address(String i, int p) {
try {
ip_addr = Resolve(i);
} catch (UnknownHostException e) {
try {
ip_addr = Resolve("127.0.0.1");
} catch (UnknownHostException ex) {
}
}
port = p;
}
public Address(InetAddress i, int p) {
ip_addr = i;
port = p;
}
public Address(int port) {
try {
ip_addr = Resolve(InetAddress.getLocalHost().getHostAddress());
this.port = port;
} catch (UnknownHostException e) {
//Trace.error("Address.Address():4", e.ToString());
}
}
public static InetAddress Resolve(String addr) throws UnknownHostException {
InetAddress ip = null;
try {
ip = InetAddress.getByName(addr);//Address(addr.getBytes());
} catch (UnknownHostException e) {
ip = DnsCache.ResolveName(addr);
}
return ip;
}
/**
* Converts an IP address in string to an equivalent byte array.
*
* @param ipaddr
* @return byte[] of IP address if ip is valid otherwise null
*/
private static byte[] ParseIPAddress(String ipaddr) {
byte[] address = null;
String[] mcast = ipaddr.split("[.]", -1);
if (mcast.length == 4) {
address = new byte[4];
try {
address[0] = (byte) (Integer.parseInt(mcast[0]));
address[1] = (byte) (Integer.parseInt(mcast[1]));
address[2] = (byte) (Integer.parseInt(mcast[2]));
address[3] = (byte) (Integer.parseInt(mcast[3]));
} catch (RuntimeException e) {
return null;
}
}
return address;
}
/**
* Checks if a specified string is a valid multi-cast ip-address.
*
* @param ipaddr
* @return
*/
public static boolean isMulticastAddress(String ipaddr) {
try {
return isMulticastAddress(ParseIPAddress(ipaddr));
} catch (RuntimeException e) {
return false;
}
}
public static boolean isMulticastAddress(InetAddress ipAddr) {
if (ipAddr != null) {
String[] mcast = ipAddr.toString().split("[.]", -1);
byte b1 = Byte.parseByte(mcast[0]);
byte b2 = Byte.parseByte(mcast[1]);
byte b3 = Byte.parseByte(mcast[2]);
byte b4 = Byte.parseByte(mcast[3]);
if ((b1 < 224) || (b1 > 240)) {
return false;
}
if ((b1 == 224) && (b3 < 1)) {
return false;
}
return true;
}
return false;
}
/**
* Checks if the specified IP address in byte[] array is a valid IP multicast Address.
*
* @param ipAddr
* @return
*/
private static boolean isMulticastAddress(byte[] ipAddr) {
if (ipAddr != null && ipAddr.length == 4) {
if ((ipAddr[0] < 224) || (ipAddr[0] > 240)) {
return false;
}
if ((ipAddr[0] == 224) && (ipAddr[2] < 1)) {
return false;
}
return true;
}
return false;
}
public static Address Parse(String address) throws UnknownHostException {
String[] hostPort = address.split("[:]", -1);
return new Address(hostPort[0], Integer.parseInt(hostPort[1]));
}
public final InetAddress getIpAddress() {
return ip_addr;
}
public final int getPort() {
return port;
}
public final boolean getMulticastAddress() {
return ip_addr != null ? isMulticastAddress(ip_addr) : false;
}
public final byte[] getAdditionalData() {
return additional_data;
}
public final void setAdditionalData(byte[] value) {
this.additional_data = value;
}
/**
* Establishes an order between 2 addresses. Assumes other contains non-null Address. Excludes channel_name from comparison.
*
* @return 0 for equality, value less than 0 if smaller, greater than 0 if greater.
*/
public final int compare(Address other) {
return this.compareTo(other);
}
/**
* implements the java.lang.Comparable interface
*
* @param o - the Object to be compared
* @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
* @throws java.lang.ClassCastException - if the specified object's type prevents it from being compared to this Object.
* @see java.lang.Comparable
*/
public final int compareTo(Object o) {
int h1 = 0, h2 = 0, rc;
if ((o == null)) //|| !(o is Address))
//throw new System.InvalidCastException("Address.compareTo(): comparison between different classes");
{
return 1;
}
Address other = (Address) ((o instanceof Address) ? o : null);
if (other == null) {
return 1;
}
if (ip_addr == null) {
if (other.ip_addr == null) {
return port < other.port ? -1 : (port > other.port ? 1 : 0);
} else {
return -1;
}
}
h1 = ip_addr.hashCode();
if (other.ip_addr != null) {
h2 = other.ip_addr.hashCode();
}
rc = h1 < h2 ? -1 : (h1 > h2 ? 1 : 0);
return rc != 0 ? rc : (port < other.port ? -1 : (port > other.port ? 1 : 0));
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
return this.compareTo(obj) == 0 ? true : false;
}
@Override
public int hashCode() {
int retval = ip_addr != null ? ip_addr.hashCode() + port : port;
return retval;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (ip_addr == null) {
sb.append("");
} else {
//if (isMulticastAddress(ip_addr))
if (ip_addr.isMulticastAddress()) // Love java for this
{
sb.append(ip_addr.getHostAddress());
} else {
String host_name = null;
if (resolve_dns) {
try {
host_name = DnsCache.ResolveAddress(ip_addr);
} catch (UnknownHostException ex) {
Logger.getLogger(Address.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
host_name = ip_addr.getHostAddress(); //Love java for this too
}
appendShortName(host_name, sb);
}
}
sb.append(":" + port);
// if (additional_data != null)
// sb.Append(" (extra: ").Append(additional_data.Length).Append(" bytes)");
return sb.toString();
}
/**
* Input: "daddy.nms.fnc.fujitsu.com", output: "daddy". Appends result to string buffer 'sb'.
*
* @param hostname The hostname in long form. Guaranteed not to be null
* @param sb The string buffer to which the result is to be appended
*/
private void appendShortName(String hostname, StringBuilder sb) {
int index = hostname.indexOf((char) '.');
if (hostname == null) {
return;
}
if (index > 0 && !Character.isDigit(hostname.charAt(0))) {
sb.append(hostname.substring(0, (index) - (0)));
} else {
sb.append(hostname);
}
}
public final Object clone() {
Address ret = null;
ret = new Address(ip_addr.getHostAddress(), port);
if (additional_data != null && ret != null) {
ret.additional_data = new byte[additional_data.length];
System.arraycopy(additional_data, 0, ret.additional_data, 0, additional_data.length);
}
return ret;
}
public final void DeserializeLocal(ObjectInput reader) throws UnknownHostException, IOException {
int bytesToRead = reader.readInt();
if (bytesToRead > 0) {
byte[] ip = new byte[bytesToRead];
reader.read(ip, 0, bytesToRead);
if (ip != null) {
try {
ip_addr = InetAddress.getByAddress(ip);
} catch (Exception e) {
//e.printStackTrace();
}
}
}
port = reader.readInt();
bytesToRead = reader.readInt();
if (bytesToRead > 0) {
additional_data = new byte[bytesToRead];
reader.read(additional_data, 0, bytesToRead);
}
}
public final void SerializeLocal(ObjectOutput writer) throws IOException {
byte[] ip = ip_addr != null ? ParseIPAddress(ip_addr.getHostAddress()) : null;
if (ip != null) {
writer.writeInt(ip.length);
writer.write(ip);
} else {
writer.writeInt(0);
}
writer.writeInt(port);
if (additional_data != null) {
writer.writeInt(additional_data.length);
writer.write(additional_data);
} else {
writer.writeInt(0);
}
}
///#region ICompactSerializable Members
public final void deserialize(NCacheObjectInput reader) throws ClassNotFoundException, IOException {
byte[] ip = convertToByteArray((short[]) reader.readObject());
if (ip != null) {
try {
ip_addr = InetAddress.getByAddress(ip);
} catch (Exception e) {
//e.printStackTrace();
}
}
port = reader.readInt();
additional_data = (byte[]) reader.readObject();
}
public void serialize(NCacheObjectOutput writer) throws IOException {
byte[] ip = ip_addr != null ? ParseIPAddress(ip_addr.getHostAddress()) : null;
writer.writeObject(ip);
writer.writeInt(port);
writer.writeObject(additional_data);
}
public void Serialize(CompactWriter writer) throws IOException {
byte[] ip = ip_addr != null ? ParseIPAddress(ip_addr.getHostAddress()) : null;
writer.WriteObject(ip);
writer.Write(port);
writer.WriteObject(additional_data);
}
public void Deserialize(CompactReader reader) throws IOException, ClassNotFoundException {
byte[] ip = (byte[]) reader.ReadObject();
if (ip != null) {
try {
ip_addr = InetAddress.getByAddress(ip);
} catch (Exception e) {
//e.printStackTrace();
}
}
port = reader.ReadInt32();
additional_data = (byte[]) reader.ReadObject();
}
public static Address readAddress(NCacheObjectInput reader)throws ClassNotFoundException,IOException
{
byte isNull = reader.readByte();
if (isNull == 1)
return null;
Address newAddr = new Address();
newAddr.deserialize(reader);
return newAddr;
}
public static void writeAddress(NCacheObjectOutput writer, Address addr)throws IOException
{
byte isNull = 1;
if (addr == null)
writer.write(isNull);
else
{
isNull = 0;
writer.write(isNull);
addr.serialize(writer);
}
return;
}
private byte[] convertToByteArray(short[] inputArray) {
if(inputArray == null)
return null;
byte[] outputArray = new byte[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
outputArray[i] = (byte) inputArray[i];
}
return outputArray;
}
}