Listen on 9100 for print - java

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.

Related

Monitor All outgoing/Incoming packet from a specific port

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());
}

How to exit/disconnect from telnet properly?

Im telneting into a server and it will block the port if I do not disconnect properly. Im already using socket.close(); so I am not sure what I am doing wrong to disconnect completely from the server
//java socket client example
import java.io.*;
import java.net.*;
public class socket_client {
public static void main(String[] args) throws IOException {
Socket s = new Socket();
String host = "1.1.1.1";
PrintWriter s_out = null;
BufferedReader s_in = null;
try {
s.connect(new InetSocketAddress(host, 12656));
System.out.println("Connected");
// writer for socket
s_out = new PrintWriter(s.getOutputStream(), true);
// reader for socket
s_in = new BufferedReader(new InputStreamReader(s.getInputStream()));
}
// Host not found
catch (UnknownHostException e) {
System.err.println("Don't know about host : " + host);
System.exit(1);
}
// Send message to server
String message = "this is the msg";
s_out.println(message);
System.out.println("Message send");
// Get response from server
String response;
while ((response = s_in.readLine()) != null) {
System.out.println(response);
}
// close the socket
s.close();
// close the i/o streams
s_out.close();
s_in.close();
}
}
There is no disconnect sub-protocol in Telnet. All you have to do is close the socket.
I've never seen or heard of a Telnet server 'block a port if I do not disconnect properly'. I have a production Telnet client which does only that, and which has been working correctly for five or six years. And any server at all that doesn't handle unexpected disconnections properly has something very seriously wrong with it.
The problem is elsewhere, possibly in the (unspecified) server itself. To behave as you describe, it would have to completely ignore end of stream conditions, and ignore IOExceptions as well (or else treat them as completely fatal to the entire process). It would also have to be single-threaded. I'm finding it rather difficult to believe in the existence of such a server, or indeed this problem.
NB you only need to close 's_out', the outermost stream/writer you've wrapped around the socket output stream. If you must close the input stream and the socket, do so after closing the output stream/writer.
The socket is blocked since the server side is not handling unexpected socket closing. You have two alternatives - or rather, two steps, if you want to be thorough - to fixing this.
Handle the other end of the connection closing unexpectedly in an
exception handler, and closing the socket when needed.
Having the client send a message to the server when it wants to
close the connection, allowing the server to close the socket, and
then handling that closed socket as a successful operation.
This is an example of server socket code from O'Reilly that gracefully handles unexpected termination:
try {
ServerSocket server = new ServerSocket(5776);
while (true) {
Socket connection = server.accept( );
try {
OutputStreamWriter out
= new OutputStreamWriter(connection.getOutputStream( ));
out.write("You've connected to this server. Bye-bye now.\r\n");
connection.close( );
}
catch (IOException e) {
// This tends to be a transitory error for this one connection;
// e.g. the client broke the connection early. Consequently,
// we don't want to break the loop or print an error message.
// However, you might choose to log this exception in an error log.
}
finally {
// Most servers will want to guarantee that sockets are closed
// when complete.
try {
if (connection != null) connection.close( );
}
catch (IOException e) {}
}
}
catch (IOException e) {
System.err.println(e);
}

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.

What is the benefit of creating an unconnected socket in Java?

In the code I'm studying, I see this line:
Socket clientSocket = new Socket();
So this is just a raw socket, connecting to nowhere? Why would you use this kind of socket that is not bound to a port?
I see on the API that it is "with the system-default type of SocketImpl."
You do this when you want to connect with a timeout:
Socket s = new Socket();
try
{
s.connect(address, timeout);
}
catch (SocketTimeoutExceptione exc)
{
// connect timeout
}

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