MQTT - validation for incorrect IP and Port - java

I want to validate that given IP and port are running in MQTT if not then i have to show exception to user. here is my code,
try {
MqttMessage message2 = new MqttMessage();
MQTT mqtt_connect = new MQTT();
mqtt_connect.setHost(Host_Address, port);
String topic = "/call/MQTT_Config";
mqtt_connect.setClientId("MQTT_Config");
mqtt_connect.setWillRetain(false);
mqtt_connect.isWillRetain();
mqtt_connect.setWillTopic(topic);
BlockingConnection m_publisher = mqtt_connect.blockingConnection();
m_publisher.connect();
if(m_publisher.isConnected()){
System.out.println("connected");
m_publisher.disconnect();
}
else
{
System.out.println("not connected");
return "Port or IP may not running";
}
} catch (Exception e) {
e.printStackTrace();
return "failure";
}
when i give correct IP and port then it goes to if(m_publisher.isConnected()) condition fine but when i give wrong IP or port then it comes till m_publisher.connect(); and then there is nothing happen, like loading console only.Is not going to next step. why?
i have to show some validation when user give unmatched IP or MQTT port. where am i doing wrong?

The problem here will depend on what the user enters.
If they enter an IP address for a machine that exists but is not listening on the port then the machine will respond quickly with a connection refused message
If they enter an IP address for a machine that doesn't exist then the code will wait for the TCP timeout (default is 15mins) before raising an error.

Related

java.net.ConnectException/java.net.ConnectException depending on normal run or debug mode

Hi am trying to send a binary message to a server with the IP and Port:
192.168.2.101:10001
The socket is reopened every 50 messages.
If I run the application normally I get a java.net.ConnectException in line 5, even though I can ping and telnet the server.
If I debug the application I get a java.net.SocketException at a different line (11), also sometimes the first message seems to get through without any errors.
private void sendMessage(String message, int relaisId, long timestamp) {
try {
if (connCount > 50) {
s = new Socket(ip, port); //RUN NORMALLY: java.net.ConnectException: Connection refused: connect
connCount=0;
}
outputStream = s.getOutputStream();
outputStream.write(message.getBytes());
outputStream.write(new byte[]{0});//DEBUG: java.net.SocketException: Connection reset by peer: socket write error
outputStream.flush();
connCount++;
} catch (UnknownHostException ex) {
logger.error("Host not found: " + ip + ":" + port, ex);
connCount=51;
retryMessage(message, relaisId, timestamp);// basically sleep 3s then call sendMessage
} catch (IOException ex) {
logger.error("Error at Relais No. " + relaisId + ": " + ip + ":" + port, ex);
connCount=51;
retryMessage(message, relaisId, timestamp); // basically sleep 3s then call sendMessage
} finally {
try {
if (connCount > 50 && s != null) {
s.close();
}
} catch (IOException ex) {
logger.error("IOException", ex);
}
}
}
Any help or analysis tools are very much appreciated :)
I found the solution. In my program different Threads send messages to external hardware components over given IPs and Ports.
This error occured because a Thread accidently got initiated twice with the same IP address and port, resulting in timing conflicts while using the same socket.
Even more strange was, that this error started to occur permanently while changing the server machine, before it was only there sporadically and we thought it was a noise in the network communication.
Hope this is a help to anyone in the future :)

How to check Internet availability in Java using nslookup?

Currently I am using URL()
public boolean isInternetAvailable(){
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
urlConnect.setConnectTimeout(5000);
Object objData = urlConnect.getContent();
return true;
} catch (Exception e) {}
return false;
}
But In the requirement, we don't want to use any URL. We want to ping localhost if connection is available than return true otherwise flase.
For nslookup I am using
try
{
InetAddress inetAddress = InetAddress.getByName("localhost");
System.out.println("Host: " +inetAddress.getHostName());
System.out.println("IP Address: " +inetAddress.getHostAddress());
System.out.println("IP Address: " +inetAddress.isSiteLocalAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
But I am not understand how to check the connection availability with nslookup.
Please suggest best approach for it. Thanks
There are several catches to this question:
Starting with the most specific one - connecting to localhost: even if your computer does not have a network card, it will be able to resolve localhost on a loopback interface and connect to itself (if there is an open port).
Your DNS may be down/misconfigured, so you cannot resolve example.com but you can connect to it by IP (93.184.216.34) - does that mean than "internet is not available"?
The firewall in your company may be blocking certain sites, but allowing other - does that mean than "internet is not available"?
The server of example.com is down while all the other sites in the world work fine. Does that mean than "internet is available" or not?
The firewall in your company may be allowing HTTP connections only on standard ports 80 and 443 and disallowing other. Thus, http://example.com connects, but http://example.com:12345 does not. Does that mean than "internet is available" or not?
So the only question you can actually ask is whether you can connect to a particular host on a particular port using its domain name and/or its IP address.
Figured out a final solution using NetworkInterface:
Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces();
while(eni.hasMoreElements()) {
Enumeration<InetAddress> eia = eni.nextElement().getInetAddresses();
while(eia.hasMoreElements()) {
InetAddress ia = eia.nextElement();
if (!ia.isAnyLocalAddress() && !ia.isLoopbackAddress() && !ia.isSiteLocalAddress()) {
if (!ia.getHostName().equals(ia.getHostAddress()))
return true;
}
}
}
I have got solution from here:- Java Quickly check for network connection

How create SSL Socket with IPv6 IP addresses?

In the client, I get the address of the server after an UDP multicast (IPv6).
So, I have the server's IPv6 address and I want a create a socket linked to it :
Below you will find extracts from my code that I hope will help you to understand the exception I get.
I get an error when I want to create the SSLSocket :
client.java
try{
System.out.println("IP: \n"+this.IP_ADDRESS);
this.sslSocketFactory = this.sslContext.getSocketFactory();
this.sslSocket = (SSLSocket) this.sslSocketFactory.createSocket(this.IP_ADDRESS, this.CLIENT_PORT);
}
catch (java.rmi.UnknownHostException e){
System.err.println("Don't know about host: " + this.IP_ADDRESS);
}
catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: " + this.IP_ADDRESS);
}
Output
IP:
/fda8:6c3:ce53:a890:0:0:0:1
Couldn't get I/O for the connection to: /fda8:6c3:ce53:a890:0:0:0:1
I'm wondering if there is an exception because of the IP format (that "/" in front of the address) or because its an IPv6 address.
Type of IP_ADDRESS is InetAddress
EDIT 1
Here is how I get the IP Address :
I send UDP Datagrams to the server and I check its response :
// Check if message is correct
String message = new String(receivePacket.getData()).trim();
System.out.println(message);
if (message.equals("SERVER_POSITIVE_RESPONSE")){
this.IP_ADDRESS = receivePacket.getAddress();
break;
}
EDIT 2
I had e.printStackTrace and here is what I get
java.net.ConnectException: Connection refused: connect

Java socket - client and server IP address

I am writing a program with TCP sockets connection between client and server. When the server starts I want to display the IP and port that clients need to use to connect, and when client connects I want the server to show what IP did the client connect from. I am getting confused which command should i use to each of those:
getInetAdress()
getLocalAdress()
getRemoteSocketAdress()
edit
I earlier used int port = 1234 and String IP = "localhost" to test and it worked, but I only used it on one PC, so I think localhost will not work if i start server and client on different computers.
This is server side:
int port = 1234;
...
public void start() {
keepRunning = true;
// create socket
try {
ServerSocket server = new ServerSocket(port);
while (keepRunning) {
display("Waiting for client connections on "
+ server.getInetAddress().getLocalHost()
.getHostAddress() + ":" + port);
Socket conn = server.accept();
if (!keepRunning)
break;
ClientThread t = new ClientThread(conn);
cList.add(t);
t.start();
And this is client:
int port = 1234;
String IP = "localhost";
//these variables can be changed from Client GUI before making connection
...
public boolean start() {
try {
socket = new Socket(IP, port);
} catch (Exception e) {
display("Error connectiong to server:" + e);
return false;
}
try {
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
display("Exception creating new Input/output Streams: " + e);
return false;
}
When i start the server,
display("Waiting for client connections on " + server.getInetAddress().getLocalHost().getHostAddress() + ":" + port);
return this:
Waiting for client connections on 192.168.1.104:1234
which is kind of what i want, but I still cant get it to show me the port. 1234 is a fixed value i used, but I want to use ServerSocket server = new ServerSocket(0); to asign port dynamically, then when i start the client i just put in the values that i got from server and connect.
I tried to use server.getLocalPort() in the display line in server and it returned 55410 or something like that, but when i put this port in client to make connection, it doesn't work. I get Error connectiong to server:java.net.ConnectException: Connection refused: connect. from client
To get the current port that the ServerSocket is listening to, use getLocalPort();
http://download.java.net/jdk7/archive/b123/docs/api/java/net/ServerSocket.html#getLocalPort%28%29
getLocalPort
public int getLocalPort()
Returns the port number on which this socket is listening.
If the socket was bound prior to being closed, then this method will continue to return the port number after the socket is closed.
Edit: Just saw your edit. Are you trying to connect by explicitly referencing the IP and Port? If so, and it's still failing, your server machine might be running a firewall. I'd check for that first.

What name do i use to connect to a server socket in java

I am writing a telnet like program in java using the server socket and socket classes. This is my current code for the client program. The user types in the server name and the port they would like to connect on.
static Socket getSocket()
{
while(true)
{
System.out.println("What server do you want to connect to on which port?");
String info = sc.nextLine();
String host = info.split(" ")[0];
int port = Integer.parseInt(info.split(" ")[1]);
try
{
InetAddress ip = InetAddress.getByName(host);
return new Socket(ip, port);
}
catch (UnknownHostException e)
{
System.err.println("The host is unknown.");
}
catch (IOException e)
{
System.err.println("Network error.");
}
}
}
I tried connecting on localhost, and it worked. Then i tried connecting with my friend on a remote computer using the ip address as the network name and it did not work giving an exception. What name do i use to connect to a remote server.
You need to give your friend your remote IP address.

Categories