Java UDP Port 161 scan - java

Port 161 is used by SNMP. I wrote a small peice of code to check if a device is running SNMP on this port.
public boolean isPortOpen(String ip, int port, int timeout) {
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), timeout);
socket.close();
logger.info(threadId, "Port is Open : " + ip + ":" + port );
return true;
} catch (IOException ex) {
logger.error(threadId, "isPortOpen : " + ip + ":" + port + "\t"+ ex.getMessage());
return false;
}
}
However to my surprise the code always returns false for port 161 even though the box is running SNMP and other tools such as PortQryV2 return true for port 161. Can someone please help!! TIA

Related

Not able to publish: MQTT client is not connected in java

When i run my code it's working fine but after some hours it stop working and show this error Not able to publish: MQTT client is not connected
public Mqtt5AsyncClient connect(String host, int port) {
Mqtt5AsyncClient client = MqttClient.builder().useMqttVersion5()
.identifier(UUID.randomUUID().toString())
.serverHost(host)
.serverPort(port).buildAsync();
Mqtt5ConnAck connectionAck = null;
try {
connectionAck = client.toBlocking().connect();
Mqtt5ConnAckReasonCode connAckCode = connectionAck.getReasonCode();
logger.debug("Client connected to broker with url: " + host + ":" + port + " ::Connection ack code: " + " keep alive ");
} catch (Exception ex) {
logger.debug("Not able to connect to broker with url: " + host + ":" + port);
ex.printStackTrace();
}
return client;
}

Java client cant connect with NodeJS server on heroku

So I have this Javascript server:
const net = require('net');
var port = process.env.PORT || 3001;
net.createServer(function (sock){
console.log('CONNECTED: ' + sock.remoteAddress + ":" + sock.remotePort);
sock.on('data', function(data){
console.log(data.toString());
});
sock.on('close', function(data){
console.log('DISCONNECTED: ' + sock.remoteAddress + ":" + sock.remotePort);
});
sock.on('error', function(error){
console.log(error);
});
}).listen(port, '0.0.0.0');
console.log('Listening on: ' + port);
And I use this to connect my Java client:
public void connect () {
System.out.println("Connecting with: " + host + ":" + port);
try {
this.socket = new Socket(this.host, this.port);
System.out.println("Connected!");
} catch (IOException e) {
e.printStackTrace();
}
}
And it works when I try it local but whenever I upload it to heroku it never logs a CONNECTED message or any received data so I don't think it connects.
I'm using this as ip/port to connect my client: .herokuapp.com:heroku.env.PORT not literally ofcourse, I use the port heroku gives to my application on launch since I do see the Listening on: message.
Am I doing something wrong? Or does heroku not support sockets?
Your client should connect to <appname>.herokuapp.com on port 80 or 443. The PORT var is for internal binding only.

Java Socket Client Unable to Connect to C# Socket Server

I have a use case, where I have to send data from a .NET application, to a Java application and I'm trying to do this using sockets. I have a server created using C# -
TcpListener tcpListener = null;
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
try
{
// Set the listener on the local IP address
// and specify the port.
tcpListener = new TcpListener(ipAddress, 13);
tcpListener.Start();
Console.WriteLine("The server is running at port 13...");
Console.WriteLine("The local End point is -" +
tcpListener.LocalEndpoint);
output = "Waiting for a connection...";
Console.WriteLine(output);
Socket s = tcpListener.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
}
catch (Exception e)
{
output = "Error: " + e.ToString();
Console.WriteLine(output);
}
}
On the Java side, I have created a socket which listens to the same host and port -
Socket socket;
try {
socket = new Socket( "localhost", 13);
System.out.println("Connection established");
BufferedReader input =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
I'm getting the below error - java.net.ConnectException: Connection refused: connect. I have used telnet localhost 13, to check if my server is really running, and it is. So i don't think it could be an issue with server not running or firewalls, since both are running locally. Any ideas on how to resolve this?
I tried your code and I had exactly the same problem. Your C# TCP Server only binds to the IPv6 interface (check e.g. the resource monitor listening addresses). If you change your server to new TcpListener(IPAddress.Any, 13) it should work.

No address in DatagramPacket

I am attempting to add a multiplayer form to a simple pong game, but when I try to start the DatagramPacket and try to read the IP and port it says the ip is null and the port is -1. Does anyone know why it would be doing this? I thought maybe it was because the socket hadn't recieved the packet yet, but when I look I saw that all code after socket.recieve(packet) isn't running.
Code where I start the server:
public GameServer(PongEngine engine) {
this.engine = engine;
try {
this.socket = new DatagramSocket(4269);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void run() {
while(true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
System.out.println(packet.getAddress() + ":" + packet.getPort());
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
String message = new String(packet.getData());
if(message.trim().equalsIgnoreCase("ping")) {
System.out.println("CLIENT[" + packet.getAddress() + ":" + packet.getPort() + "] > " + message);
sendData("pong".getBytes(), packet.getAddress(), packet.getPort());
}
}
}
DatagramPacket's getAddress returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.
In the first System.out.println you have just created the object, but have not done any network I/O with it.
Then you ignore the exception and just try to work with the datagram. If there was an I/O error, it's likely that the datagram was not initialized and hence still has IP address null and port -1.
If nothing happens after socket.receive() I'd assume the call is blocked, waiting for a packet to come in. Do you actually run the client that connects to your server code?
To add to Roberts answer, your code is simply out of order. Once you have that fixed then you can address why you might not be recieving a packet form the other PC like ccarton suggested.
Try this, and note the two comments
public void run() {
while(true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
//Wait for packet (The code will not move on until a packet is received or there is an error)
System.out.println("Waiting for packet");
socket.receive(packet);
//Move your socket/port info after receiving a packet so you don't get null or -1
System.out.println("Packet received: "+ packet.getAddress() + ":" + packet.getPort());
//Move your code inside try, rather than after
String message = new String(packet.getData());
if(message.trim().equalsIgnoreCase("ping")) {
System.out.println("CLIENT[" + packet.getAddress() + ":" + packet.getPort() + "] > " + message);
sendData("pong".getBytes(), packet.getAddress(), packet.getPort());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now do you still get the same issues?

What do I change my socket to?

alI created a simple text based RPG and after alot of work managed to put it on a website (www.worldofthedrakon.com). I just created a server and client but I am having problems with users accessing the server from their computer. I have my socket set up as:
Socket socket = new Socket("localhost", 8800);
Now i have tested changing localhost out for my IP, to no avail. The errors I'm getting are connection timed out, and connection refused. Could someone point me in the right direction? I apologize if my problem seems vague, more code can be provided. Theres alot of it so I didnt want to bombard you :) Thank you.
ServerSide:
public Server() {
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("Multi-Thread Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
try {
ServerSocket serverSocket = new ServerSocket(8800);
jta.append("MultiThreadServer started at " + new Date() + '\n');
int clientNo = 1;
while(true) {
Socket socket = serverSocket.accept();
jta.append("Server Thread for client " + clientNo + " at " + new Date() + '\n');
InetAddress inetAdress = socket.getInetAddress();
jta.append("Client " + clientNo + "'s host name is " + inetAdress.getHostName() + "\n");
jta.append("Client " + clientNo + "'s IP Address is " + inetAdress.getHostAddress() + "\n");
HandleAClient task = new HandleAClient(socket);
new Thread(task).start();
clientNo++;
}
} catch(IOException ex) {
System.err.println(ex);
}
Client Side:
try {
Socket socket = new Socket("localhost", 8800);
fromServer = new DataInputStream(socket.getInputStream());
toServer = new DataOutputStream(socket.getOutputStream());
} catch (IOException ex) {
jta_TextArea.setText(ex.toString() + '\n');
}
Your socket is bound to localhost this means in can only serve the local client. If you want others to see your server the first step is to bind to the IP address that is visible to those others!
I think you want to be using a ServerSocket and not a regular socket.
"localhost" is exactly that; it is your local host or your machine. If you are trying to connect your socket to some other host (like whatever resolves to www.worldofthedrakon.com), you need to get that hostname or its IP address in there.
Socket socket = new Socket("worldofthedrakon.com", 8800);
Then you get to fight the firewall issues. Connection Refused is usually an indication that there is a firewall or two in the way. Do you know that port 8800 is open on your new host?

Categories

Resources