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);
}
}
}
}
Related
I want to read out some information from a Arduino over the serial port.
I use the jSerialComm library.
Here's my code:
SerialPort serialPort = SerialPort.getCommPort("COM3");
serialPort.setComPortParameters(9600, 8, 1, 0);
if(serialPort.isOpen())
{
System.out.println("SerialPort is open");
}
else
{
System.out.println("SerialPort is not open");
}
Sadly, the program says that the port is closed, but I know it's not. I guess that I named it wrong here: SerialPort.getCommPort("COM3"); So how do I have to name it so it will work?
Not sure if any of this works (can't test atm), but I hope it does:
You could maybe look up the name in Device Manager -> Ports;
You can try running this and see what it says:
SerialPort[] list= SerialPort.getCommPorts();
if (list.length == 0) {
System.out.println("No ports found");
} else {
for (int i = 0; i < list.length; i++) {
System.out.println("Port " + i + ": " + list[i].getDescriptivePortName());
}
}
Or you could just try this and see what happens:
SerialPort serialPort = SerialPort.getCommPorts()[3];
Also, have a look at your baudrates, try with the Serial Monitor closed, and try an other USB cable.
I have to create a program that sniff a local network for school. I chose to work with Java and found out that you can capture packets with jpcap.
So I wanted to follow one of the example provided in jpcap's github and it seems like I can only find my own packets.
Like I said, I've looked at the code and chose my wifi interface. The program is capturing packets and I put all the source ip addresses in a text file to run some tests. I have also created a hashmap the ip addresses I've finded when I did a arp -a. From what I've read online, this command shows you ip addresses in your network.I created a boolean set to false and I then proceeded to run a loop that goes through the textfile and looked if the ip address was in the hashMap : if one of the addresses appeared in the hashmap, the boolean would be change to true and it would mean that I've managed to catch something.
After running the test, the boolean came out false.
Here's the example code
``public class PacketCaptor {
private static final int INFINITE = -1;
private static final int PACKET_COUNT = INFINITE;
/*
private static final String HOST = "203.239.110.20";
private static final String FILTER =
"host " + HOST + " and proto TCP and port 23";
*/
private static final String FILTER =
// "port 23";
"";
public static void main(String[] args) {
try {
if(args.length == 1){
PacketCaptor sniffer = new PacketCaptor(args[0]);
} else {
System.out.println("Usage: java Sniffer [device name]");
System.out.println("Available network devices on your machine:");
String[] devs = PacketCapture.lookupDevices();
for(int i = 0; i < devs.length ; i++)
System.out.println("\t" + devs[i]);
}
} catch(Exception e) {
e.printStackTrace();
}
}
public PacketCaptor(String device) throws Exception {
// Initialize jpcap
PacketCapture pcap = new PacketCapture();
System.out.println("Using device '" + device + "'");
pcap.open(device, true);
//pcap.setFilter(FILTER, true);
pcap.addPacketListener(new PacketHandler());
System.out.println("Capturing packets...");
pcap.capture(PACKET_COUNT);
}
}
class PacketHandler implements PacketListener
{
WritingClass writing = new WritingClass();
public void packetArrived(Packet packet) {
try {
// only handle TCP packets
if(packet instanceof TCPPacket) {
TCPPacket tcpPacket = (TCPPacket)packet;
byte[] data = tcpPacket.getTCPData();
String srcHost = tcpPacket.getSourceAddress();
String dstHost = tcpPacket.getDestinationAddress();
String isoData = new String(data, "ISO-8859-1");
System.out.println(srcHost+" -> " + dstHost + ": " + isoData);
String datas = srcHost+"|"+dstHost+"|";
writing.write(datas, this.writing.getFileName());
}
} catch( Exception e ) {
e.printStackTrace();
}
}
Can anyone help me figure out why It doesn't work ?
Thank you so much for your help
The reason why you aren't able to capture more packets is because you need an interface in promisc or raw mode, I advice you to use a proper sniffer like wireshark to check if other packets that aren't addressed to you can be captured. If not, means you need apply a mitm method because you are in a commuted network. For use that code on wifi should be enough an interface in monitor mode (check aircrack-ng suite).
In GNU/Linux Debian based systems may use the command iw dev wlan0 interface add mon0 type monitor (from package wireless-tools)
Currently I am trying to communicate with a Parallel port via Java, but this has proven to be troublesome. I am currently doing a brain research using EEG and I want to send simple "event markers" to the EEG system, which must happen via Parallel Port. I have used both javax.comm and RXTX but for some reason I cannot manage to write output to the port. The test-code is as follows:
import gnu.io.*; // RXTX
// import javax.comm.*; // javax.comm
public class PrlCom {
private String msg= "1";
private OutputStream outputStream;
private InputStream inputStream;
private ParallelPort parallelPort; // can be both Rxtx or javax.comm
private CommPortIdentifier port;
// CONSTANTS
public final String PARALLEL_PORT = "LPT1";
public final String[] PORT_TYPE = { "Serial Port", "Parallel Port" };
public static void main(String[] args) {
new PrlCom();
}
public PrlCom(){
openParPort();
}
public void openParPort() {
try {
// get the parallel port connected to the EEG-system (used to be printer)
port = CommPortIdentifier.getPortIdentifier(PARALLEL_PORT);
System.out.println("\nport.portType = " + port.getPortType());
System.out.println("port type = " + PORT_TYPE[port.getPortType() - 1]);
System.out.println("port.name = " + port.getName());
// open the parallel port -- open(App name, timeout)
parallelPort = (ParallelPort) port.open("CommTest", 50);
outputStream = parallelPort.getOutputStream();
inputStream = parallelPort.getInputStream();
System.out.println("Write...");
outputStream.write(toBytes(msg.toCharArray()));
System.out.println("Flush...");
outputStream.flush();
} catch (NoSuchPortException nspe) {
System.out.println("\nPrinter Port LPT1 not found : " + "NoSuchPortException.\nException:\n" + nspe + "\n");
} catch (PortInUseException piue) {
System.out.println("\nPrinter Port LPT1 is in use : " + "PortInUseException.\nException:\n" + piue + "\n");
} catch (IOException ioe) {
System.out.println("\nPrinter Port LPT1 failed to write : " + "IOException.\nException:\n" + ioe + "\n");
} catch (Exception e) {
System.out.println("\nFailed to open Printer Port LPT1 with exeception : " + e + "\n");
} finally {
if (port != null && port.isCurrentlyOwned()) {
parallelPort.close();
}
System.out.println("Closed all resources.\n");
}
}
I got the toBytes() function from Converting char[] to byte[] . I also directly tried spam.getBytes(), which made no difference.
After running this code with the javax.comm package, the parallel port is not recognized. If I run the code with RXTX(gnu.io), I get an IOException. The entire printed output is then as follows
Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version = RXTX-2.1-7
port.portType = 2
port type = Parallel Port
port.name = LPT1
Output stream opened
Write...
Printer Port LPT1 failed to write : IOException.
Exception:
java.io.IOException: The device is not connected.
in writeByte
Closed all resources.
With Rxtx, the code can make a connection with the Parallel Port thus. However, it is unable to write a byte to the output stream. Can someone please tell me how to resolve this?
I have read in many of the other topics how outdated a parallel port is and that I should use USB. However, I am working with an EEG-system (BioSemi ActiveTwo with ActiView software) to measure brain activity and, sadly, I don't have the possibility to change this. A Parallel port-USB converter is also no option. (Odd though, that something so technologically advanced uses such outdated hardware).
Thank you so much!
I have accepted that Rxtx and javax.comm do not work anymore. Instead, I found a workaround via Python. For the answer, see
Parallel Port Communication with jnpout32pkg / jnpout32reg
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
I'm starting to dive into obtaining IP addresses through Java. I understand that a machine can have various IPs through different network interfaces, so I'm somewhat confused about some sample code I've found that appears to return the "Preferred" IP address (Preferred per Windows 7 command line ipconfig /all).
When I run the following code on my local computer, 26 NetworkInterface objects are returned, some with multiple InetAddress objects (including the "Preferred" one):
Enumeration<NetworkInterface> eNI = null;
NetworkInterface ni = null;
Enumeration<InetAddress> eIA = null;
InetAddress ia = null;
try {
eNI = NetworkInterface.getNetworkInterfaces();
} catch (Exception e) {
}
while (eNI.hasMoreElements()) {
ni = eNI.nextElement();
System.out.println("NtwkIntfc name: " + ni.getName());
System.out.println("NtwkIntfc disp name: " + ni.getDisplayName());
try {
System.out.println("NtwkIntfc hardware addr: " + Hex.encodeHexString(ni.getHardwareAddress()));
} catch (Exception e) {
}
eIA = ni.getInetAddresses();
while (eIA.hasMoreElements()) {
ia = eIA.nextElement();
System.out.println("InetAddress host address: " + ia.getHostAddress());
System.out.println("InetAddress host name: " + ia.getHostName());
}
}
However this much simpler code simply returns the "Preferred" IPv4 address:
try {
InetAddress thisIp = InetAddress.getLocalHost();
System.out.println("IP:" + thisIp.getHostAddress());
} catch (Exception e) {
e.printStackTrace();
}
I can't seem to find the NetworkInterface (and InetAddress from it) property/method that identifies it as "Preferred", so I'm wondering how the class method InetAddress.getLocalHost() does it? And furthermore, is this Preferred IP a standard networking concept or some type of Windows specific concept?
Thanks.
take a look at metric in network settings. also look at "route print" under windows 7 command line. i think the lower the metric the more "preferred" the adapter is.
Check out the source code for InetAddress.getLocalHost().
Briefly, it gets the IP addresses bound to the host name, and returns the first entry from the returned array of IP addresses.
I don't see anything specific to this being preferred, other than it's an address mapped to the machine hostname (note however a machine can have multiple names too)
I think 'Preferred' may somehow refer to the most general entry in the routing table. Who knows what those Windows crazies were thinking.
However, this address may also correspond to the address that is most likely to be a public IP/assigned by DHCP. If you're looking for code that gets the most likely address to be public/used to open a port on, this is what I use to get an IPv4 address:
public static InetAddress getNetworkAddr() {
InetAddress localAddr = null;
// Find our public IP address
Enumeration<NetworkInterface> netInterfaces;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while( addresses.hasMoreElements() ) {
InetAddress addr = addresses.nextElement();
// System.out.println("Checking out " + ni.getName() + " with address " + addr.toString());
if (!addr.isSiteLocalAddress() &&
!addr.isLoopbackAddress() &&
!addr.isLinkLocalAddress() &&
addr.getHostAddress().indexOf(":") == -1) { // MAC/IPv6 address detection
System.out.println("Interface " + ni.getName()
+ " seems to be InternetInterface. I'll take address " + addr.toString());
System.out.println("Associated hostname: " + addr.getHostName());
localAddr = addr;
break;
}
}
if( localAddr != null ) break;
}
} catch( NoSuchElementException e) {
System.out.println("Couldn't find a public address");
localAddr = null;
} catch (SocketException e) {
e.printStackTrace();
localAddr = null;
}
return localAddr;
}
An other solution seams to work with sockets (not the best one)
Socket socket = new Socket("www.somesite.com", 80);
InetAddress localhost = socket.getLocalAddress();
System.out.println("Address of local host is " + localhost);
socket.close();