Java: Hostname lookup not working with InetAddress & org.xbill.DNS - java

I have been trying to write code in Java to do a DNS reverse lookup (look up hostname from given IP).
I have tried the following ways to do it.
InetAddress addr1 = InetAddress.getByName("11.121.5.67");
String host = addr1.getHostName();
byte[] ipAddr = new byte[] {(byte)34, (byte)195, (byte)110, (byte)15};
host = InetAddress.getByAddress(ipAddr);
String hos = host.getCanonicalHostName();
Using org.xbill.DNS Library
lookup = new Lookup(ipaddress,Type.ANY);
Resolver resolver = new SimpleResolver();
lookup.setResolver(resolver);
lookup.setCache(null);
Record[] records = lookup.run();
byte[] ipAddr = new byte[] {(byte)15, (byte)110, (byte)195, (byte)34};
Resolver res = new ExtendedResolver();
Name name = ReverseMap.fromAddress(ipAddr);
int type = Type.PTR;
int dclass = DClass.IN;
Record rec = Record.newRecord(name, type, dclass);
Message query = Message.newQuery(rec);
Message response = res.send(query);
Record[] answers = response.getSectionArray(Section.ANSWER);
But none of these options work. I am able to get the IP address from FQDN using InetAddress. But not reverse with any of the above options.
Should I setup the ResolverConfig or any other configuration before I use org.xbill.DNS for doing DNS Lookup?
Basically, I want to do DNSlookup in an organization level network systems.
I am a newbie to Java and these libraries. Any help would be greatly appreciated.

Related

SnmpV3 Trap Receiver with Authentication/Privacy - dynamically obtain engineID from agents

I am trying to develop an SNMPv3 Trap Receiver using the WebNms AdventNet API.
If I use authentication and privacy options (MD5 + DES), I need to know the engineID of the Agent that sends the traps in
order to decrypt the trap content. How can I obtain this engineID dynamically (without hardcoding it in my application)?
I saw that it's possible to perform a discovery of the engineID
But for this to work I need to provide the port used by the Agent when sends the traps (and the agent is a real network element which uses random source ports).
The following code is working, but I hard-coded the engineID.
Is there a different way to decrypt the traps without hardcoding the engineID?
public class DragosApp2 implements SnmpClient{
public static void main(String[] args) throws SnmpException {
SnmpAPI api = new SnmpAPI();
SnmpEngineEntry snmpEntry = new SnmpEngineEntry("10.10.66.79");
SnmpEngineTable engineTable = api.getSnmpEngine();
engineTable.addEntry(snmpEntry);
SnmpSession session = new SnmpSession(api);
session.addSnmpClient(new DragosApp2());
UDPProtocolOptions ses_opt = new UDPProtocolOptions();
ses_opt.setLocalPort(162);
session.setProtocolOptions(ses_opt);
session.open();
byte[] engineID = gethexValue("0x80001f888026f9036957333c81"); // HOW can I replace this part??
USMUserEntry user = new USMUserEntry(new String("dragos3").getBytes(), engineID);
user.setAuthProtocol(USMUserEntry.MD5_AUTH);
user.setPrivProtocol(USMUserEntry.CBC_DES);
byte[] authKey = USMUtils.password_to_key(USMUserEntry.MD5_AUTH,
new String("12345678").getBytes(),
new String("12345678").getBytes().length,
engineID);
byte[] privKey = USMUtils.password_to_key(USMUserEntry.MD5_AUTH,
new String("12345678").getBytes(),
new String("12345678").getBytes().length,
engineID,
USMUserEntry.CBC_DES);
user.setAuthPassword(new String("12345678").getBytes());
user.setPrivPassword(new String("12345678").getBytes());
user.setAuthKey(authKey);
user.setPrivKey(privKey);
user.setSecurityLevel((byte)3);
user.setEngineEntry(snmpEntry);
USMUserTable uut = (USMUserTable)api.getSecurityProvider().getTable(3);
uut.addEntry(user);
}
}

Setting connection's `max_frame_size` in Qpid Proton AMQP 1.0 client library

I would like to simply open an AMQP 1.0 connection with a specific max_frame_size using the Apache Qpid Proton client library. This is inside a testsuite, not a real world application.
The Java library seems more advanced than the C library and its various bindings for other languages, so I started to use the Java one. Unfortunately, I can't find a way to set this parameter, though there must be a way: there is this Transport class which offers to get or set max_frame_size.
I first tried with the Messenger API, then I played with the Engine API. I couldn't figure out how to access the transport instance. In the case of the Engine API, I see there is a Connection.getTransport() and tried that, but it's NULL at the time I call this function.
Here is my last test:
private void do_test_with_frame_size(int frame_size, int payload_size) {
Connection conn = Connection.Factory.create();
Transport transport = conn.getTransport();
transport.setMaxFrameSize(frame_size);
Session session = conn.session();
Sender sender = session.sender("sender");
conn.open();
session.open();
sender.open();
if (sender.getCredit() > 0) {
String uri = System.getProperty("broker_uri");
assertNotNull(uri);
String address = String.format("%s/fragmentation-%d-%d",
uri, frame_size, payload_size);
Message message = Proton.message();
message.setAddress(address);
message.setBody(new AmqpValue(new byte[payload_size]));
byte[] msgData = new byte[1024];
int length;
while(true) {
try {
length = message.encode(msgData, 0, msgData.length);
break;
} catch(BufferOverflowException e) {
msgData = new byte[msgData.length * 2];
}
}
byte[] tag = "0".getBytes();
Delivery delivery = sender.delivery(tag);
sender.send(msgData, 0, length);
delivery.settle();
sender.advance();
sender.close();
sender.getSession().close();
sender.getSession().getConnection().close();
}
}
I admit I have very limited knowledge of Java. Could you please confirm it is even possible to set this parameter and, if yes, tell me how to?
You need to create a Transport instance for the connection to use and then bind the transport to the connection instance. A created Connection does not have an implicit Transport bound to it which is why you get a null returned to you currently.
private final Transport protonTransport = Proton.transport();
private final Connection protonConnection = Proton.connection();
...
this.protonTransport.setMaxFrameSize(maxFrameSize);
this.protonTransport.setChannelMax(CHANNEL_MAX);
this.protonTransport.bind(this.protonConnection);

Jacob connect to Remote Computer for WMI support

I'm trying to connect to a remote computer using java and Jacob in order to get some WMI Information about the remote computer.
For localhost I'm using the code below and it works fine.
String host = "localhost";
String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
ActiveXComponent axWMI = new ActiveXComponent(connectStr);
// other code to get system information
But if I change localhost to another ip/hostname I got the following error:
Exception in thread "main" com.jacob.com.ComFailException: Can't find moniker
at com.jacob.com.Dispatch.createInstanceNative(Native Method)
at com.jacob.com.Dispatch.<init>(Dispatch.java:99)
at com.jacob.activeX.ActiveXComponent.<init>(ActiveXComponent.java:58)
at easyticket.classes.WmiExtended.main(WmiExtended.java:28)
and the row that throws the exception is:
ActiveXComponent axWMI = new ActiveXComponent(connectStr);
EDIT
I tried passing username/password using WbemScripting
String host = "192.168.7.106";
ActiveXComponent axWMI = new ActiveXComponent("WbemScripting.SWbemLocator");
axWMI.invoke("ConnectServer", new Variant(host+",\"root\\cimv2\",\"username\",\"password\""));
but I got this error:
Exception in thread "main" com.jacob.com.ComFailException: Invoke of: ConnectServer
Source: SWbemLocator
Description: The RPC server is unavailable.
How can I solve it? How can I pass username/password and if is needed the domain???
I'm using Windows 8 and I'm trying to connect to win8/win7/winxp/win2003server computers.
After some searches I managed to solve my problem...
Here's the code if anyone need it.
ActiveXComponent wmi = new ActiveXComponent("WbemScripting.SWbemLocator");
Variant variantParameters[] = new Variant[4];
variantParameters[0] = new Variant(_IPADDRESS);
variantParameters[1] = new Variant("root\\cimv2");
variantParameters[2] = new Variant("username");
variantParameters[3] = new Variant("password");
ActiveXComponent axWMI;
try
{
Variant conRet = wmi.invoke("ConnectServer", variantParameters);
axWMI = new ActiveXComponent(conRet.toDispatch());
}catch(ComFailException e)
{
axWMI = null;
}
if (axWMI == null)
return false;

Cannot deserialize featureset using DigitalPersona Sdk java edition

am trying to create a soap webservice method to match fingerprints using digitalpersona one touch for windows sdk java edition. I capture the featureset from an applet at the client side and compare it with my template on the server side. But I need to deserialize it and create the feature set again so that i can compare it with the template.
I dont know how to recreate the feature set so that i can use it for verification:
//This is for template retrieval: (no problem here)
String dbTemplate = result.getString("template");
byte[] byteArray = new byte[1];
byteArray = hexStringToByteArray(dbTemplate);
DPFPTemplate template = DPFPGlobal.getTemplateFactory().createTemplate();
template.deserialize(byteArray);
byte[] fsArray = new byte[1];
fsArray = hexStringToByteArray(ftSet);
//the problem is here, I've already converted it back into bytearray[] but i need to deserialize it and create the feature set again.
featureSet.deserialise(fsArray);
DPFPFeatureSet features = extractFeatures(sample, DPFPDataPurpose.DATA_PURPOSE_VERIFICATION);
//This is for matching features and template
DPFPVerification matcher = DPFPGlobal.getVerificationFactory().createVerification();
DPFPVerificationResult result1 = matcher.verify(features, template);
if (result1.isVerified()) {
return "The fingerprint was VERIFIED.";
} else {
return "The fingerprint was NOT VERIFIED.";
}
Please help me.
the best thing you can do here is not to convert the bytearray into string. if you are saving it in a database, you can automatically save it as byte array (since the blob can accept a bytearray).
you can insert it like this (just an example)
PreparedStatement st=con.prepareStatement("INSERT INTO EMPLOYEE(employee_id,template)"+"values(?,?)");
st.setInt(1,23);
st.setBytes(2, enroller.getTemplate().serialize());
Statement st = con.createStatement();
ResultSet rec = st.executeQuery("SELECT * FROM EMPLOYEE WHERE EMPLOYEE_ID=3");
Then when accessing the template, deserialize it (just follow the sdk, i think it's around page 37) Onetouch java sdk ==== link
a sample will be available below.
while(rec.next()){
blob = rec.getBlob("template");
int blobLength = (int)blob.length();
blobAsBytes = blob.getBytes(1, blobLength);
}
templater.deserialize(blobAsBytes);
verificator.setFARRequested(DPFPVerification.MEDIUM_SECURITY_FAR);
DPFPVerificationResult result = verificator.verify(fs, templater);
if (result.isVerified())
System.out.print("The fingerprint was VERIFIED.");

Get queues depth from java code

Can anyone help in doing the code in java of getting the depth of the queues. We are having 4 queues in IBM WebSphere MQ and inside them there are messages.
I want to write a jsp to read the queue names and their depth while running the report. How do I do that?
Can anyone help in getting the full solution because I don't know what to do
I doens't think there is a way to retrieve the queue depth using JMS. You can however use MQ Series specific Java API to retrieve this information. Here is the sample code. Pay attention to int openOptions = MQC.MQOO_INQUIRE;
Here is the reference guide
int depth = 0;
MQQueueManager qMgr; // define a queue manager object
String mqHost = "";
String mqPort = "";
String mqChannel = "";
String mqQMgr = "";
String mqQueue = "";
try {
// Set up MQSeries environment
MQEnvironment.hostname = mqHost;
MQEnvironment.port = Integer.valueOf(mqPort).intValue();
MQEnvironment.channel = mqChannel;
MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY,
MQC.TRANSPORT_MQSERIES);
qMgr = new MQQueueManager(mqQMgr);
int openOptions = MQC.MQOO_INQUIRE;
MQQueue destQueue = qMgr.accessQueue(mqQueue, openOptions);
depth = destQueue.getCurrentDepth();
destQueue.close();
qMgr.disconnect();
} catch (Exception err) {
err.printStackTrace();
}
If you install the WMQ client from the IBM download (as opposed to just grabbing the class libs from the QMgr installation) you get sample code. Among the samples provided are several that list queue names, inquire on object properties and create objects. In a default installation on Win 7 these can be found at C:\Program Files (x86)\IBM\WebSphere MQ\tools\pcf\samples.
Download the WMQ client libraries here:
WMQ v6.0 is SupportPac MQC6 (End of life is September 2012)
WMQ v7.0 is SupportPac MQC7
WMQ v7.1 is SupportPac MQC71
The SupportPac landing page is here.
You are STRONGLY encouraged to use the latest WMQ client for any new development. It will work for all prior versions of WMQ at whatever level of functionality is provided by the target QMgr. Please see the Compatibility & Interop statement in the Infocenter. You can find the Infocenter for the WMQ version of server or client that you are using from the WMQ Library landing page.
A few of these functions are depreciated in IIB, so am pasting the updated code. It works :)
Enjoy
Getting MQ Queue Depth From Java:
try {
int depth = 0;
MQQueueManager qMgr; // define a queue manager object
String mqHost = "";
String mqPort = "";
String mqChannel = "";
String mqQMgr = "";
String mqQueue = "";
try {
// Set up MQSeries environment
MQEnvironment.hostname = mqHost;
MQEnvironment.port = Integer.valueOf(mqPort).intValue();
MQEnvironment.channel = mqChannel;
//MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY,MQC.TRANSPORT_MQSERIES);
qMgr = new MQQueueManager(mqQMgr);
//int openOptions = 1;//MQC.MQOO_INQUIRE;
int openOptions = CMQC.MQOO_INQUIRE + CMQC.MQOO_FAIL_IF_QUIESCING + CMQC.MQOO_INPUT_SHARED;
MQQueue destQueue = qMgr.accessQueue(mqQueue, openOptions);
depth = destQueue.getCurrentDepth();
destQueue.close();
qMgr.disconnect();
MbMessage outMessage = new MbMessage();
outAssembly = new MbMessageAssembly(inAssembly, outMessage);
MbElement root = outMessage.getRootElement();
MbElement outXmlRoot = root.createElementAsLastChild(MbXMLNSC.PARSER_NAME);
MbElement Appointment = outXmlRoot.createElementAsLastChild(MbElement.TYPE_NAME, "RootElementXMLName", null);
Appointment.createElementAsLastChild(MbElement.TYPE_NAME_VALUE, "Q_DepthFromServer", depth);
out.propagate(outAssembly);
}

Categories