I am implementing a Sniffer using Jpcap in Netbeans.
The code is given below.
It works fine in the terminal and gives me the correct output.
Now when i try to develop a gui to selecte the network interface and show the captured packets in a table the problem arises.
import jpcap.*;
import jpcap.NetworkInterface;
import jpcap.packet.DatalinkPacket;
import jpcap.packet.EthernetPacket;
import jpcap.packet.ICMPPacket;
import jpcap.packet.IPPacket;
import jpcap.packet.Packet;
import jpcap.packet.TCPPacket;
import jpcap.packet.UDPPacket;
class Te implements PacketReceiver {
static int i = 0;
String protocoll[] = {"HOPOPT", "ICMP", "IGMP", "GGP", "IPV4", "ST", "TCP", "CBT", "EGP", "IGP", "BBN", "NV2", "PUP", "ARGUS", "EMCON", "XNET", "CHAOS", "UDP", "mux"};
public void receivePacket(Packet packet) {
System.out.println(packet + "\n");
System.out.println("this is packet " + i + " :" + "\n");
i++;
IPPacket tpt=(IPPacket)packet;
if (packet != null) {
int ppp=tpt.protocol;
String proto=protocoll[ppp];
System.out.println("about the ip packet in network layer : \n");
System.out.println("******************************************************************");
if(tpt.dont_frag){
System.out.println("dft bi is set. packet will not be fragmented \n");
}else{
System.out.println("dft bi is not set. packet will be fragmented \n");
}
System.out.println(" \n destination ip is :"+tpt.dst_ip);
System.out.println("\n this is source ip :"+tpt.src_ip);
System.out.println("\n this is hop limit :"+tpt.hop_limit);
System.out.println(" \n this is identification field :"+tpt.ident);
System.out.println(" \npacket length :"+tpt.length);
System.out.println("\n packet priority :"+(int)tpt.priority);
System.out.println("type of service field"+tpt.rsv_tos);
if(tpt.r_flag){
System.out.println("releiable transmission");
} else {
System.out.println("not reliable");
}
System.out.println("protocol version is : "+(int)tpt.version);
System.out.println("flow label field"+tpt.flow_label);
System.out.println("**********************************************************************");
System.out.println("datalink lavel analysis");
System.out.println("********************************************************************");
DatalinkPacket dp = packet.datalink;
EthernetPacket ept=(EthernetPacket)dp;
System.out.println("this is destination mac address :"+ept.getDestinationAddress());
System.out.println("\n this is source mac address"+ept.getSourceAddress());
System.out.println("*********************************************************************");
System.out.println("this is about type of packet");
System.out.println("******************************************************************************");
if (proto.equals(("TCP"))) {
System.out.println(" /n this is TCP packet");
TCPPacket tp = (TCPPacket) packet;
System.out.println("this is destination port of tcp :" + tp.dst_port);
if (tp.ack) {
System.out.println("\n" + "this is an acknowledgement");
} else {
System.out.println("this is not an acknowledgment packet");
}
if (tp.rst) {
System.out.println("reset connection ");
}
System.out.println(" \n protocol version is :" + tp.version);
System.out.println("\n this is destination ip " + tp.dst_ip);
System.out.println("this is source ip"+tp.src_ip);
if(tp.fin){
System.out.println("sender does not have more data to transfer");
}
if(tp.syn){
System.out.println("\n request for connection");
}
} else if(proto.equals("ICMP")){
ICMPPacket ipc=(ICMPPacket)packet;
// java.net.InetAddress[] routers=ipc.router_ip;
//for(int t=0;t
// System.out.println("\n"+routers[t]);
// }
System.out.println(" \n this is alive time :"+ipc.alive_time);
System.out.println("\n number of advertised address :"+(int)ipc.addr_num);
System.out.println("mtu of the packet is :"+(int)ipc.mtu);
System.out.println("subnet mask :"+ipc.subnetmask);
System.out.println("\n source ip :"+ipc.src_ip);
System.out.println("\n destination ip:"+ipc.dst_ip);
System.out.println("\n check sum :"+ipc.checksum);
System.out.println("\n icmp type :"+ipc.type);
System.out.println("");
} else if(proto.equals("UDP")){
UDPPacket pac=(UDPPacket)packet;
System.out.println("this is udp packet \n");
System.out.println("this is source port :"+pac.src_port);
System.out.println("this is destination port :"+pac.dst_port);
}
System.out.println("******************************************************");
}
}
public static void main(String str[]) throws Exception {
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
boolean lt;
for (int i = 0; i <devices.length; i++) {
System.out.println(i + " :" + devices[i].name + "(" + devices[i].description + ")");
System.out.println(" data link:" + devices[i].datalink_name + "("
+ devices[i].datalink_description + ")");
System.out.println();
for (NetworkInterfaceAddress a : devices[i].addresses) {
System.out.println(" address:" + a.address + " " + a.subnet + " "
+ a.broadcast);
}
}
JpcapCaptor jpcap = JpcapCaptor.openDevice(devices[0], 2000, true, 20);
jpcap.loopPacket(-1, new Te());
}
}
My Netbeans gui for the sniffer is this.
Capture GUI
I use a Combox to list the devices and use a buttion to capture the packets from the device andshow it in a table.
The problem arises here . To capture the packet infinetely
JpcapCaptor jpcap = JpcapCaptor.openDevice(devices[indexfromcombox], 2000, true, 20);
jpcap.loopPacket(-1, new Te());
Now Te is a class that implements PacketReceiver. In my Netbeans gui First itself as the control goes to the frame . How can i can a new class from the frame which will implement my Packetreceiver function and display it in a table. From terminal it was easy as Te is the only class invloved and from main i could call Te. But in Netbeans as the main will set the Frame to be visible first. The whole control goes to the frame and i am not able to call a call loopPacket function
jpcap.loopPacket(-1, new {A class which would let me capture the packet on the device selcetd}());
How can i call another class from the JFrame.java code itself to make this possible.
I hope you understood my problem and will assist me. I am in dire need of help as this is my project and cannot show the o/p in terminal .
Thanks
Related
I've been searching for a solution for this problem for 2 days now..
I have an android chat application that I want to implement sending files into it.
Here's the sending code:
public void sendFile(Uri uri) {
FileTransferManager fileTransferManager = FileTransferManager.getInstanceFor(app.getConnection());
OutgoingFileTransfer fileTransfer = fileTransferManager.createOutgoingFileTransfer(userId + "/Spark");
try {
fileTransfer.sendFile(new File(uri.getPath()), "this is the description");
System.out.println("status is:" + fileTransfer.getStatus());
System.out.println("sent .. just");
while (!fileTransfer.isDone()) {
if (fileTransfer.getStatus() == FileTransfer.Status.refused) {
Toast.makeText(getActivity(), "File refused.", Toast.LENGTH_SHORT).show();
return;
}
if (fileTransfer.getStatus() == FileTransfer.Status.error) {
Toast.makeText(getActivity(), "Error occured.", Toast.LENGTH_SHORT).show();
return;
}
}
System.out.println(fileTransfer.getFileName() + "has been successfully transferred.");
System.out.println("The Transfer is " + fileTransfer.isDone());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
I know this code works fine as I sent file from android to spark and received it successfully.. The problem is in receiving that file in android.. Here's the code:
ProviderManager.addIQProvider("si", "http://jabber.org/protocol/si",
new StreamInitiationProvider());
ProviderManager.addIQProvider("query", "http://jabber.org/protocol/bytestreams",
new BytestreamsProvider());
ProviderManager.addIQProvider("open", "http://jabber.org/protocol/ibb",
new OpenIQProvider());
ProviderManager.addIQProvider("close", "http://jabber.org/protocol/ibb",
new CloseIQProvider());
ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
final FileTransferManager manager = FileTransferManager.getInstanceFor(connection);
manager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(FileTransferRequest request) {
IncomingFileTransfer transfer = request.accept();
try {
File file = new File(Environment.getExternalStorageDirectory() + "/" + request.getFileName());
Log.i("Tawasol", "File Name: " + request.getFileName());
transfer.recieveFile(file);
while (!transfer.isDone() || (transfer.getProgress() < 1)) {
Thread.sleep(1000);
Log.i("Tawasol", "still receiving : " + (transfer.getProgress()) + " status " + transfer.getStatus());
if (transfer.getStatus().equals(org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error)) {
// Log.i("Error file",
// transfer.getError().getMessage());
Log.i("Tawasol",
"cancelling still receiving : "
+ (transfer.getProgress())
+ " status "
+ transfer.getStatus() + ": " + transfer.getException().toString());
transfer.cancel();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
still receiving : 0.0 status Negotiating Stream
I get this log for about 5 seconds the I get that:
cancelling still receiving : 0.0 status Error: org.jivesoftware.smack.SmackException: Error in execution
I think that the problem is in the openfire server that I'm using.. I've openfire 3.9.3 server installed on my windows 7 64bit.. In the Smack logs I noticed this one:
<iq id="L87BF-73" to="59xrd#rightsho/Smack" type="set" from="h97qa#rightsho/Spark"><query xmlns="http://jabber.org/protocol/bytestreams" sid="jsi_4840101552711519219" mode="tcp"><streamhost jid="proxy.rightsho" host="192.168.56.1" port="7777"/></query></iq>
The host here is 192.168.56.1 which I think is local ip so that I can't access it from android.. So I wan't to use the IP of the pc to transfer files..
Excuse me for my lack of knowledge in this field.
From my little knowledge of smack the issue may be in this piece of code:
while (!transfer.isDone() || (transfer.getProgress() < 1)) {
Thread.sleep(1000);
Log.i("Tawasol", "still receiving : " + (transfer.getProgress()) + " status " + transfer.getStatus());
if (transfer.getStatus().equals(org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error)) {
// Log.i("Error file",
// transfer.getError().getMessage());
Log.i("Tawasol",
"cancelling still receiving : "
+ (transfer.getProgress())
+ " status "
+ transfer.getStatus() + ": " + transfer.getException().toString());
transfer.cancel();
break;
}
}
If you move the monitoring while loop to another thread, suddenly this error goes away. I'm not sure why, but it has worked for me and my friends in the past.
Today I was trying to write some, lets say, internet communicator.
I'm learning basics of Java (from instructables) and now it's time for network programming.
What I want my program to do:
If there is any data on input stream from network - get data, put it into string and print in a console.
If there is data in console - put it into string and send it by network.
When I try only send data from client app to server and print it in server console - everything works fine. But then I have different code (without getting and sending data two way).
I know that problem is in lines inside while(true) statements in line if(cin.hasNextLine()). I don't understand why it blocks whole app when it should be just returning false or true if there isn't or there is data in console (from keyboard).
The annoying is that it's working perfectly with reading files.
Oh. And also I tried to check IF data which I didn't typed into console is "". It didn't solved my problem.
Server code:
import java.net.*;
import java.io.*;
import java.util.*;
import java.time.LocalTime;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port, 0);
serverSocket.setSoTimeout(30000);
}
public void run() {
while(true) {
try {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress());
FileWriter plik = new FileWriter("/home/greg/Dokumenty/logizserwera.txt", true);
System.out.println("StartTime: " + LocalTime.now());
Scanner cin = new Scanner(System.in);
String stringReadyToSend, stringGotFromClient = null;
while(true) {
System.out.println("Before hasnextline");
if(cin.hasNextLine()) {
stringReadyToSend = cin.nextLine();
out.writeUTF(stringReadyToSend);
}
if(in.available() != 0) {
stringGotFromClient = in.readUTF();
// EOT means End Of Transmission
if(stringGotFromClient.equals("EOT")) break;
else System.out.println("Message from client: " + stringGotFromClient();
}
else System.out.println("No message");
break;
}
System.out.println("EndTime: " + LocalTime.now());
server.close();
plik.close();
}
catch(SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
}
catch(IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
int port = 6066;
try {
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e) {
e.printStackTrace();
}
}
}
And client code:
import java.net.*;
import java.io.*;
import java.util.*;
public class GreetingClient {
public static void main(String[] args) {
String serverName = "localhost";
Scanner cin = new Scanner(System.in);
int port = 6066;
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
String lineReadyToSend, lineGotFromServer;
while(cin.hasNextLine()) {
if(cin.hasNextLine()) {
// EOT means End Of Transmission
lineReadyToSend = cin.nextLine();
if(lineReadyToSend.equals("EOT")) {
out.writeUTF(lineReadyToSend);
break;
}
else out.writeUTF(lineReadyToSend);
}
if(in.available() != 0) {
lineGotFromServer = in.readUTF();
System.out.println("Message from server: " + lineGotFromServer);
}
}
out.writeUTF("EOT");
client.close();
System.out.println("End of transmission. Server disconnected");
}catch(IOException e) {
e.printStackTrace();
}
}
}
You are using cin which is a Scanner for the System.in
Practically that just scans if there are entered lines on the console. Perhaps try doing that with the data input stream (in) on your server.
Well, everything looks god. Just a cuestion, do you execute both applications at same time? Well, if it's the case, could be the access to System.in resource. Remember this is a static field, and not instantiated. Try to run one of them in other location. A second hint: use try clause and watch the errors if there are, and use debuging or resource monitor tools to detect the problem.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Chat_Server extends JFrame
{
// total number of clients that can be logged on to the message service
final int NO_OF_CLIENTS = 4;
// this ArrayList will store the client threads
ArrayList<Chat_ServerThread> chatClients = new ArrayList<Chat_ServerThread>();
// arrays containing valid names and passwords
String[] names = {"Adam Smith", "Bill Allen", "Cathy Clark", "Davina Doe"};
String[] passwords = {"LuQezz169", "amG4tyz", "Dw1wU9wy", "Fre195Ufm"};
// array containing valid chat tags
String [] chattag = {"Arken", "Ben", "DarkLark", "Free", "group"};
// this array indicates whether a client is currently logged on
boolean loggedOn[] = new boolean[NO_OF_CLIENTS];
// GUI components
JTextArea outputArea;
//Other Declartations
ServerSocket serverSocket;
DataInputStream serverInputStream;
DataOutputStream serverOutputStream;
public Chat_Server()
{ super("Chat_Server");
addWindowListener
( new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
try
{ // gets a serversocket and binds to port 6000
serverSocket = new ServerSocket(6000);
}
catch(IOException e) // thrown by ServerSocket
{ System.out.println(e);
System.exit(1);
}
// create and add GUI components
Container c = getContentPane();
c.setLayout(new FlowLayout());
// add text output area
outputArea = new JTextArea(17,30);
outputArea.setEditable(false);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
c.add(outputArea);
c.add(new JScrollPane(outputArea));
setSize(360,310);
setResizable(false);
setVisible(true);
}
void getClients()
{ // add message to server output area
addOutput("Server is up and waiting for a connection...");
int userCount = 0;
while(userCount < NO_OF_CLIENTS)
{ try
{ /* client has attempted to get a connection to server,
create a socket to communicate with this client */
Socket client = serverSocket.accept();
// get input & output streams
ObjectInputStream serverInputStream = new ObjectInputStream(client.getInputStream());
ObjectOutputStream serverOutputStrean = new ObjectOutputStream(client.getOutputStream());
// add message to server output area
addOutput("Server is up and waiting for a connection...");
// read encrypted username from input stream & decrypt
EncryptedMessage uname = (EncryptedMessage)serverInputStream.readObject();
uname.decrypt();
// read encrypted password from input stream & decrypt
EncryptedMessage pword = (EncryptedMessage)serverInputStream.readObject();
pword.decrypt();
// add messages to server output area
addOutput("\nLogin Details Received\n----------------------------------------");
addOutput("encrypted username : " + uname.getMessage());
addOutput("encrypted password : " + pword.getMessage());
boolean valid = false;
int pos = Arrays.binarySearch(names, uname);
if(pos >= 0)
{ if(passwords[pos].equals(pword) && !loggedOn[pos])
{ addOutput("Login details received from client " + (userCount+1) + ", " + uname + " are valid");
addOutput("Client " + uname + " is known as " + chattag[pos]);
valid = true;
loggedOn[pos] = true;
// send Boolean value true to client
output.writeObject(new Boolean(true));
This returns an error on output. saying that it cannot be resolved
// add this new thread to the array list
Chat_ServerThread chatClient = new Chat_ServerThread (serverInputStream, serverOutputStream, names[pos], chattag[pos]);
This returns an error within the Chatserver thread. I'm also getting errors on output.writeobject. I'm not sure why it is doing this hopefully someone will be able to shed some light on things. it says that the constructor is not defined
chatClients.add(chatClient);
// start thread - execution of the thread will begin at method run
chatClient.start();
userCount++;
}
}
if(!valid)
{ /* user is not registered therefore write a Boolean value
false to the output stream */
output.writeObject(new Boolean(false));
addOutput("Login details received from client " + (userCount+1) + ", " + uname + " are invalid");
}
}
It seems that you have not created the instance of output. Try first initializing it with a constructor for whatever class it is you want output to be an instance of.
Regarding the constructor not being defined, check the constructor(s) for the Chat_ServerThread class and ensure that the arguments you are passing to the constructor match those which are defined in one of Chat_ServerThread's implemented constructors.
I have the following Java method, which I am trying to use to filter PDU messages that are received over a network, and display only the PDUs which match the filter criteria to the user:
public static void displayFilteredPdu(){
try{
EspduReceiver.socket = new MulticastSocket(EspduSender.PORT);
EspduReceiver.address = InetAddress.getByName(EspduSender.DEFAULT_MULTICAST_GROUP);
EspduReceiver.socket.joinGroup(EspduReceiver.address);
while(EspduReceiver.stopCapture == false){
byte buffer[] = new byte[EspduReceiver.MAX_PDU_SIZE];
EspduReceiver.packet = new DatagramPacket(buffer, buffer.length);
EspduReceiver.socket.receive(EspduReceiver.packet);
Pdu pdu = EspduReceiver.pduFactory.createPdu(EspduReceiver.packet.getData());
if(pdu != null){
System.out.print("Got PDU of type: " + pdu.getClass().getName());
if(pdu instanceof EntityStatePdu){
EntityID eid = ((EntityStatePdu)pdu).getEntityID();
Vector3Double position = ((EntityStatePdu)pdu).getEntityLocation();
System.out.println(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] ");
System.out.println("Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "] ");
/*Add PDU to ArrayList of PDUs */
EspduReceiver.espdu.add(pdu);
/* System.out.println(" PDU added to arrayList. ");
System.out.println(espdu); /*This is printing out the actual DIS messages (i.e. edu.nps.moves.dis.EntityState...),
maybe try adding the 'eid.getSite()', etc to an ArrayList instead. Use Associative arrays/ map/ hashmap */
// if(eid.getSite() != 0){
Filter.sitesToBeFiltered.add(eid.getSite());
System.out.println("Entity Site added to ArrayList. ");
// } else if(eid.getApplication() != 0){
Filter.applicationsToBeFiltered.add(eid.getApplication());
System.out.println("Entity Application added to ArrayList. ");
Filter.IDsToBeFiltered.add(eid.getEntity());
System.out.println("Entity ID added to ArrayList");
Filter.positionsToBeFilteredX.add(position.getX());
System.out.println("Entity X position added to ArrayList. ");
Filter.positionsToBeFilteredY.add(position.getY());
System.out.println("Entity Y position added to ArrayList. ");
Filter.positionsToBeFilteredZ.add(position.getZ());
System.out.println("Entity Z position added to ArrayList. ");
int i;
getFilterConditions();
for(i = 0; i < sitesToBeFiltered.size(); i++){
if(sitesToBeFiltered.get(i) == filter1Value){
//public double xPos = new Double();
Gui.displayFilteredOutput.append("\n");
Gui.displayFilteredOutput.append("EID: [" + sitesToBeFiltered.get(i) + ", " + applicationsToBeFiltered.get(i) + ", " + IDsToBeFiltered.get(i) + "]. ");
double filteredX = positionsToBeFilteredX.get(i);
double filteredY = positionsToBeFilteredY.get(i);
double filteredZ = positionsToBeFilteredZ.get(i);
//Vector3Double filteredEntityPosition =
Gui.displayFilteredOutput.append("\n Location in DIS coordinates: [" + filteredX + ":" + filteredY + ":" + filteredZ + "]. ");
}
}
}
}
}
}
catch(Exception e){
System.out.println(e);
e.printStackTrace();
System.out.println("Error in displayFilteredPdu() method. ");
/*09/04/2014 # 17:100
* If this exception gets called, presumably it either means that pdu is not an instance of EntityStatePdu, or
* that pdu does not actually hold a packet. */
}
}
This method is currently in a class called Filter.java, and is called when the user clicks a 'Filter' button on the GUI, and will continue to be called until the value of the variable stopCapture is changed to false (which will happen when the user clicks a 'stop' button on the GUI).
However, it is not quite behaving as I was hoping when called at the moment: currently, when the user clicks the 'Filter' button, all of the System.out.println statements are displayed in the console, so clearly the while loop is being entered, but I don't see anything displayed in the GUI, which I think would indicate that the for loop at the end of the while loop is not being entered... and also, the GUI stops responding...
As I understand, the reason that the GUI stops responding is probably because I am currently using a single threaded program, and so moving this displayFilteredPdu() method to another thread might stop the GUI from crashing, and I can then work on the other issues with the method.
I have tried doing this by moving the method to another class (called FilteredPdu.java), which extends Filter, and changing the button ActionListener() to call the method from the new class, i.e. FilteredPdu.displayFilteredPdu();, but I am still getting the same problem with the GUI crashing.
Any ideas why this is?
i think moving it in another class will still cause your program to be stuck in infinite loop.
try and make a class the extends Thread, put display filter pdu method as:
this is the new thread class:
public class YourThreadClass extends Thread{
String fake_input_in_thread = null;
public YourThreadClass(String fake_input){
//constructor
//save the input / whatever you need to pass in from the other class here, and use it later
fake_input_in_thread = fake_input
}
public void run() {
//your filter code
try{
//now you can use the value pass-in from you main class. This should display "testing123" in console.
System.out.println(fake_input_in_thread);
EspduReceiver.socket = new MulticastSocket(EspduSender.PORT);
EspduReceiver.address = InetAddress.getByName(EspduSender.DEFAULT_MULTICAST_GROUP);
EspduReceiver.socket.joinGroup(EspduReceiver.address);
.............................
}
//put the below method into the thread class
public void endOfFilter(){
EspduReceiver.stopCapture = false;
}
}
when you GUI needs to trigger that method, here's what your main class will looks like
//initialize
YourThreadClass thread = null;
public static void displayFilteredPdu(){
if(thread ==null){
//This string is to demostrate how you'd pass variables into your custom class, does not have any actual use
String str = "testing123";
thread = new YourThreadClass(str);
thread.start();
}
}
//in main code
public static void stopFilteredPdu(){
if(thread != null){
thread.endOfFilter();
thread = null;
}
}
I want to detect list of USB Ports which are free (not occupied) in system to while I checked with CommPortIdentifier.getPortIdentifiers() while this returns me Enumeration with 0 elements
I'd add librxtxcomm.jar too in classpath.
This should return each Port detail
Enumeration pList = CommPortIdentifier.getPortIdentifiers();
System.out.println(pList.hasMoreElements());
this returns 0 mean no List/Enumeration.
Rest Code :
public class CommPortLister{
/** Simple test program. */
public static void main(String[] ap) {
new CommPortLister().list();
}
/** Ask the Java Communications API * what ports it thinks it has. */
protected void list() {
// get list of ports available on this particular computer, by calling static method in CommPortIdentifier.
System.out.println("");
Enumeration pList = CommPortIdentifier.getPortIdentifiers();
System.out.println("Before While");
// CommPortIdentifier.getPortIdentifiers();
// Process the list.
System.out.println(pList.hasMoreElements());
while (pList.hasMoreElements()) {
System.out.println("While Loop");
CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();
System.out.print("Port " + cpi.getName() + " ");
if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println("is a Serial Port: " + cpi);
} else if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
System.out.println("is a Parallel Port: " + cpi);
} else {
System.out.println("is an Unknown Port: " + cpi);
}
}
System.out.println("After While");
}
}
Code to detect USB port while i am unable to detect USB Port
Please try using ServerSocket(portNo). If there is an service running in the port, it will error so catch the exception and try the next port.
A port number is a 16-bit unsigned integer, thus ranging from 1 to 65535.
If you need to know which ports are occupied, you may call the system command "netstat" from java.
================Edited===========================
The above information is for transport layer logical ports.If you are looking for hardware ports for peripheral devices, then you need to check the COM ports. I found the following tutorial, maybe you can give it a try, so find another tutorial that suits your need.
http://www.java-samples.com/showtutorial.php?tutorialid=11
You will need javax.comm api for this. You can grab it from http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm or http://www.oracle.com/technetwork/java/index-jsp-141752.html
Well here the thing using that u can have available ports u can scan it.
public class GettingAvaliable {
public static void main(String args[]) {
int startPortRange = 0;
int stopPortRange = 65365;
int usedport = 0;
int unusedports = 0;
for (int i = startPortRange; i <= stopPortRange; i++) {
try {
Socket ServerSok = new Socket("127.0.0.1", i);
System.out.println("Port in use: " + i);
usedport++;
ServerSok.close();
} catch (Exception e) {
//e.printStackTrace();
}
System.out.println("Port not in use: " + i);
unusedports++;
if (i == stopPortRange) {
System.out.println("Number of Used Ports In Your Machine: "+usedport);
System.out.println("Number of Unused Ports In Your Machine: "+unusedports);
}
}
}
}