Java - get COM port id - java

I'm writing a java program, and right now I have a setup-file which contains a COM port number. which has to be changed if the device changes COM port number.
This is not very user friendly. Therefore I want to be able to get a list of COM port ID's and let the user select the right device by its ID. I've tried googling, but without much success.
By ID I mean if you check the Device Manager: "COM Port ID (COM<#>)". Check the with red marked text seen in the following picture:
I have tried the following libraries:
javax.comm - CommPortIdentifier,getPortIdentifiers();
jssc - SerialPortList.getPortNames();
But I have been unable to find out if it is possible to get the COM port ID, as the two above methods just return the number of the COM Port. Does anyone know of a way to get the COM port IDs?

I used rxtxcomm.jar and rxtxSerial.dll to communicate with an Arduino. This snippet should get you the available ports:
#SuppressWarnings("unchecked")
Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = portEnum.nextElement();
System.out.println(currPortId.getName() + " - " + currPortId.getCurrentOwner());
}
Here's an article with some further details: https://blog.henrypoon.com/blog/2010/12/25/installing-rxtx-for-serial-communication-with-java/

Related

jSerialComm: dynamically detect available serial ports (hotplug device)

I've created a Java GUI which lists all serial ports in a drop down menu from which the user selects the correct port and clicks connect. Connection to an Arduino is then established and the user is able to perform some actions. I get the available ports using Fazecast JSerialComm:
SerialPort[] ports = SerialPort.getCommPorts();
I grab the ports and put the results into the drop down. This works flawlessly BUT only when the Arduino is plugged into the Mac BEFORE launching my Java GUI. Is there a way to detect a hotplugged device in Java? I already thought of getting the com ports periodically (every second or so) but to me that does seem to be a very elegant solution.
update:
I found this answered by another user:
Serial communication manager have APIs to find serial port names like COMxx dynamically. Just connect your USB-USRT IC and SCM library will tell you the device node for it. Just google for Serial communication manager. It is hosted on GitHub.
src
You might do this by checking if the port is opened or not after trying to open it using:
SerialPort[] serialPorts = SerialPort.getCommPorts();
SerialPort liveSerialPort = null;
for (SerialPort p: serialPorts) {
p.openPort();
if (p.isOpen()) {
liveSerialPort = p;
System.out.println("HERE opened port = " + liveSerialPort.getSystemPortName());
break;
}
}

PcapNetworkInterface returns null on given IP

I am trying to capture packages. In my "exploration" example I use the IP of a website that I visit in the browser. I am using PCAP4J to capture package information.
Based on step 3 on https://www.pcap4j.org/ I have the impression that I can simply have an internet address and start listening to it:
InetAddress addr = InetAddress.getByName("192.168.10.100");
PcapNetworkInterface nif = Pcaps.getDevByAddress(addr);
However, when I change this ip to my personal example (185.57.10.32) the nif returns null.
I have printed out a list of PcapNetworkInterfaces as follows:
System.out.println("#### LIST OF DEVS ####");
List<PcapNetworkInterface> devices = Pcaps.findAllDevs();
for (PcapNetworkInterface device : devices) {
System.out.println(device.getName());
}
System.out.println("###############");
Which returns the following:
wlp2s0
any
lo
docker0
enp3s0f1
br-df16c72d2764
bluetooth0
nflog
nfqueue
usbmon1
usbmon2
So in that sense I understand that nif returns null as it is not in the list. However, it makes me not understand why the example given by the author is not workign as I expect.
So I think the first question would be: Can one listen to a specific ip via Pcap4J? In this case an ip of a website. Or are websites not possible and should I make another test case?
Thank you!
An IP addreess you should pass to Pcaps.getDevByAddress() is one a NIF has.
You can capture packets from any IP addresses with the NIF.

Creating a DHCP client list java

I'm trying to write a program that will show a DHCP client list in Java. I want to get the IP addresses, MAC addresses and the host names of all the devices connected to my wifi network.
I have a Belkin router. Its homepage has a 'DHCP client list' option which when clicked shows me this table :
That's exactly what I'm looking for. But I want to show all this data in the form of a list in a Java Swing program. I also want to be able to update this list by pressing a refresh button. Is there any way to achieve this?
It should look something like this :
I've written a basic java program that shows all the IP addresses that are online. Here's the code :
public static void main(String[] args) throws IOException {
InetAddress localhost = InetAddress.getLocalHost();
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 1; i <= 254; i++)
{
ip[3] = (byte)i;
InetAddress address = InetAddress.getByAddress(ip);
if (address.isReachable(1000))
{
// machine is turned on and can be pinged
System.out.println(address + "is online");
}
else if (!address.getHostAddress().equals(address.getHostName()))
{
// machine is known in a DNS lookup
System.out.println(address + "is in a DNS lookup");
}
else
{
// the host address and host name are equal, meaning the host name could not be resolved
System.out.println(address + " is not online");
}
}
}
But this doesn't serve the purpose and it's really slow. I want to write a Swing program that'll show me the DHCP client list as seen in the image above.
Any help is appreciated.
I would think about three possible alternatives:
1-The one you implemented that is slow but it can work. You need to find a JAVA API to get the MAC addresses of received messages (I don't know if it exists or not). You can also send ARP messages asking "who has this IP address) and obtain the MAC address from the response. Use some Java interface for pcap library: jNetPcap vs Jpcap , http://jnetpcap.com/
2-Create an app that accesses your router web interface using HTTP and sending the appropriate messages with data as if you were using the UI. In this way you can programatically follow the steps a human would go and get the list that you browser shows, parse it and obtain the data.
3-If the router/access point provides a web API, which I doubt, you can use it.

Java server-client game

Ok, I am quite new to network programming and I am trying to solve this problem:
I have GUI based Java SE game for max 7 players and I want it to support multiplayer over the Internet.
Every instance of game would have its own client sending and receiving string.
And here comes the problem I cannot sufficiently solve. I need server and its only functionality is keeping client's sockets opened and on receiving some string just forward it to other clients. My first idea was to run server on the first player's machine and other players can connect to that server via its IP from outside. Now I discovered that getting public interface IP is not that easy as I thought so I searched and found the code written below to get some IP's that SHOULD be available from outside. When I try this at localhost, resulted IP is always some IPv6 + port and connecting from client using this credentials is successful and it works. When I start the server on another machine and copy these credentials for connecting from another computer it fails (it either doesn't connect or if it does and client sends message, server doesn't receive any).
So my next idea was to use some public IP on remote hosting server. So there would be some server running 24/7 (or if I programmatically from game tell him so) and I use its IP to unite all clients. I just don't know how to make this thing working and what technologies use.
I hope I explained my problem clearly and thanks for any ideas or even solutions :)
Get machine's public interface IP (where server is running) and prints that out code:
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
if (iface.isLoopback() || !iface.isUp()) { //127.xxx loopback
continue;
}
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
String tmp = addr.getHostAddress();
if (tmp.startsWith("192.168.") //local IP
|| tmp.startsWith("10.") //local IP
|| tmp.startsWith("172.16.") //local IP
|| tmp.startsWith("172.31.") //local IP
|| tmp.startsWith("169.254") //single network IP
|| tmp.equals("255.255.255.255")) { //broadcast address
continue;
}
//cut "%net9","%wlan" etc stuff off
IP = tmp.substring(0, Math.max(0, tmp.indexOf('%')));
port=server.getPort();
System.out.println(IP + " " + port);
}
}
if running on a "local network" then having a serversocket is fine, but we deal with NAT and the internet which means that 98% of machines are not directly internet visible. (i.e. opening a TCP port for listening on the machine will not result in the machines Internet IP address having that port be listened to. )
The initial option would be to have a server on public hosting which mediates communication between players and each players machine is responsible for maintaining 'game state' but then you run into the issue of synchronization. (e.g. one players machine thinks that they have hit and killed another player prior to that machine receiving a command to tell it that the opponent has moved. )
The current method of thinking for this paticular problem is to have the server maintain the 'game state' (e.g. player positions, health, weapon damage, etc. )
having players send 'commands' to the server (e.g. move, fire, jump. ) and then having the server report to all players the 'minor' game state changes. (so Time becomes an important factor and all messages between clients and server need to be timestamped. )
so your clients maintain what they believe 'game state' to be, recieving updates from the server to 'correct' errors.
In addition to this every once in a while the server should send a dump of the entire 'game state' to each player as a 'sync' message to ensure what they believe to be the game state 'is' the actual game state.
If your language of choice was "C" it would be trivial to take the md5 checksum of the entire game state structure and then transmit this to players periodically and only performing a sync message..
The links below should give you a good starting point.
A good start
And the enclosing page with a little bit more detail

How do i select correct active serial port in linux?

I am trying to communicate with a microcontroller using java.
In windows i simply use "COM4" and my code workes perfectly.
In linux i am trying to use "/dev/ttyUSB0". But gives me an error "Could not find serial port".
I used dmesg | grep tty to see active serial port. is this a right method?
how can i solve this issue? I am really new to linux so please explain in simple language
here is my code
Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
CommPortIdentifier portId = null;
while (portIdentifiers.hasMoreElements())
{
CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();
if(pid.getPortType() == CommPortIdentifier.PORT_SERIAL &&
pid.getName().equals("/dev/ttyUSB0"))
{
portId = pid;
break;
}
}
if(portId == null)
{
System.err.println("Could not find serial port "); // + wantedPortName);
System.exit(1);
}
lsusb should show you the serial to USB converter
lsusb | grep -i serial
gives on my system
Bus 001 Device 005: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port
and
ls -l /dev/ttyUSB*
crw-rw---- 1 root dialout 188, 0 Feb 18 10:30 /dev/ttyUSB0
I can then access it with
cat /dev/ttyUSB0
The user, who needs access to the port, must be in the group dialout or whatever group it is in your system. You can add the user with
adduser <user-name> dialout
Apparently java communication API do not have linux implementation http://www.oracle.com/technetwork/java/index-139971.html thats why my code wasn't working.
I installed RXTX library for serial communication and code is working fine now.
Thanks nos and Olaf Dietsche for the help and support.

Categories