Monitor All outgoing/Incoming packet from a specific port - java

I'm trying to monitor a port to get the outgoing/incoming packets (or sockets) from my PC using Java, more like what Wireshark does.
I'm using this code:
int portNumber = 5816;
try {
System.out.println("New ServerSocket...");
ServerSocket serverSocket = new ServerSocket(portNumber);
serverSocket.setSoTimeout(5000);
System.out.println("Accepting...");
serverSocket.accept();
System.out.println("Done Accepting.");
} catch (IOException e) {
System.out.println(e.getMessage());
}
Now I can see the packets using Wireshark, and I can see the connection is established using Process Hacker 2, but I always get this output:
New ServerSocket... Accepting... Accept timed out
EDIT:
The question,
I got an application installed, that exchange packets with an external server (nor the client or the server are mine), i just want to intercept these packets and log them.
and they are using 5816 port.

Wireshark is using pcap library to intercept network communication. You can use pcap wrapper for java to achieve similar functionality.
Note:
You are not closing sockets. However, this code is still incorrect approach to achieve your goal.
int portNumber = 5816;
System.out.println("New ServerSocket...");
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
serverSocket.setSoTimeout(5000);
System.out.println("Accepting...");
try(Socket socket = serverSocket.accept()) {
System.out.println("Done Accepting.");
}
} catch (IOException e) {
System.out.println(e.getMessage());
}

Related

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.

How to correctly close the socket?

Client:
Open socket:
Socket socket = new Socket(host,port);
Write data:
socket.getOutputStream().write("str");
socket.getOutputStream().flush();
Read data:
response = socket.getInputStream().read();
Close connection and socket:
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
Server:
Socket clientSocket = serverSocket.accept();
message = clientSocket.getInputStream().read();
clientSocket.getOutputStream().write("str2");
clientSocket.isConnected() returned true, and the server does not see that the client is disconnected. How to detect that the client is disconnected?
I'm try use this:
try {
while (true) {
message = clientSocket.getInputStream().read();
clientSocket.getOutputStream().write("str2");
}
} catch (IOException e) {
clientSocket.close();
}
But it doesn't work.
A common approach is that the client sends a "QUIT" message to the server. The server will then close it's socket.
The other approach is to do I/O on the server socket and catch the exceptions that you'll get when the client is gone.
The latter approach has a couple of drawbacks:
It will take some time for the server to give up trying to reach the client (that can take 2 minutes)
The error message might not always be the same. Usually, you'll just get a SocketException with the error message from your OS.

Listen on 9100 for print

How can i listen to raw printer port 9100 in Java.
When i create ServerSocket on port 9100 and accept connection nothing happens when i try to print to this port.
System.out.println("listening on 9100");
try {
ServerSocket serverSocket = new ServerSocket(9100);
serverSocket.setSoTimeout(0);
serverSocket.accept();
System.out.println("Accepted connection");
} catch (IOException e) {
e.printStackTrace();
}
EDIT: "Accepted connection" is never printed. So the socket is never initiated
You're ignoring the return value from serverSocket.accept().
This gives you back a socket. Seems you're not using it at all.
ServerSocket.accept
From that socket you then need to get input/output streams,
and then you can communicate with the client over these streams.

Checking for a client disconnect on a Java TCP server - output only

I have a Java TCP server which, when a client connects to it, outputs a message to the client every 30 seconds. It is a strict requirement that the client does not send any messages to the server, and that the server does not send any data other than the 30-second interval messages to the client.
When I disconnect the client, the server will not realise this until the next time it tries to write to the client. So it can take up to 30 seconds for the server to recognise the disconnect.
What I want to do is check for the disconnect every few seconds without having to wait, but I am not sure how to do this given that a) the server does not receive from the client and b) the server cannot send any other data. Would anyone please be able to shed some light on this? Thanks.
Even though your server doesn't "receive" from the client, a non-blocking read on the client socket will tell you that either there's nothing to be read (as you expect), or that the client has disconnected.
If you're using NIO you can simply use a non-blocking Selector loop (with non-blocking sockets) and only write on your 30 second marks. If a SelectionKey is readable and the read on the SocketChannel returns -1 you know the client has disconnected.
EDIT: Another approach with blocking is simply to select with a 30 second timeout. Any client disconnects will cause the select to return and you'll know which ones those are via the read set. The additional thing you'd need to do there is track how long you were blocked in the select to figure out when to do your writes on the 30 second mark (Setting the timeout for the next select to the delta).
Big Edit: After talking to Myn below, offering complete example:
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
// Set a 1 second timeout on the socket
clientSocket.setSoTimeout(1000);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
long myNextOutputTime = System.currentTimeMillis() + 30000;
String inputLine = null;
boolean connected = true;
while (connected)
{
try {
inputLine = in.readLine();
if (inputLine == null)
{
System.out.println("Client Disconnected!");
connected = false;
}
}
catch(java.net.SocketTimeoutException e)
{
System.out.println("Timed out trying to read from socket");
}
if (connected && (System.currentTimeMillis() - myNextOutputTime > 0))
{
out.println("My Message to the client");
myNextOutputTime += 30000;
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
Worth noting here is that the PrintWriter really moves you far away from the actual socket, and you're not going to catch the socket disconnect on the write (It will never throw an exception, you have to manually check it with checkError()) You could change to using a BufferedWriter instead (requires using flush() to push the output) and handling it like the BufferedReader to catch a disco on the write.
If you are managing multiple clients then I guess you would be using Non-Blocking sockets (If not then consider using Non-Blocking). You can use Selector to monitor all the connected sockets to check if they are readable or writeable or there is some Error on that socket. When some client disconnects, your Selector will mark that socket and will return.
For more help google "Socket Select function"

How to find which of the first 1024 ports seem to be hosting TCP based servers on a specified host?

I want to solve my problem using and I use java programming language.
Just try to connect to them with a Socket. If you don't get a ConnectException, something is listening st that TCP port. Then do the server a favor and close the socket immediately.
What's the purpose exactly?
This is a simple code to connect to a socket with a timeout
// Create a socket with a timeout
try {
InetAddress addr = InetAddress.getByName("java.sun.com");
int port = 80;
SocketAddress sockaddr = new InetSocketAddress(addr, port);
// Create an unbound socket
Socket sock = new Socket();
// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException is thrown.
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
} catch (UnknownHostException e) {
} catch (SocketTimeoutException e) {
// Could not reach host - network error.
} catch (IOException e) {
// Network error
}
You can just run this code in a loop to check a series of ports.
NOTE: real portscanners are much more sophisticated: http://art-exploitation.org.ua/7261final/lib0021.html

Categories

Resources