Check which process is using a given port - java

I'm making a simple client-server application in Java. This is how I initialise the listening socket:
private void initSock() {
try {
sock = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: "+port+". Isn't the port already in use?");
System.exit(1);
}
}
That approach throws likely usefull error message when the port is used - however: Would it be possible to extend the info, like this:
Could not listen on port xx, it's being used by process blahblah with pid xxx.
Will Java (and Windows, and eventually other systems) allow me to fetch that info?
I can find this info using command line, but that's really not what I want at this moment.

I am not being able to fulfill your requirment, but below code can give you some more info:
public class NetStat
{
public static void main(String [] args) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter port number :");
String port =br.readLine();
StringBuffer output = new StringBuffer();
Process p = Runtime.getRuntime().exec("netstat -an");
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
if(line.contains(port))
{
output.append(line + "\n");
}
}
System.out.println(output.toString());
}
}
Input: 50773
Output: TCP 1xx.xxx.xxx.xxx:50773 xxx.xxx.xxx.xxx:8080 ESTABLISHED

Related

In Java, is it possible to find out which port number is used by a known PID in UNIX systems?

I am trying to implement the best code/class in Java that can capture the port number by supplying with a known process number (PID) in Unix systems, ie Linux, Solaris and AIX. I checked with the Socket class but it doesn't seem to support this solution?
Anyone knows the better way to reach this solution?
you can use Runtime.getRuntime().exec
For Example the fallowing code shows how to get tcp socket of process with PID
2046
public static void main(String[] args) {
// TODO Auto-generated method stub
Process p=null;
StringBuffer output = new StringBuffer();
String command= "netstat -p ";
try{
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
if(line.matches("^tcp.*2406.*"))
output.append(line + "\n");
//reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(output);
}
output for this in my system was
tcp 0 0 192.168.2.239:52956 sc-in-f188.1e100.n:5228 ESTABLISHED 2406/chrome
we know the socket here is 52956 you can further parse the string for finding socket
refer
how-to-execute-shell-command-from-java

Java - BufferedReader Stalls without an Escape Character

I am building a server in Java, and the input feed is giving me trouble - its current setup cannot read more than one line, and it cannot read anything without "\n" at the end. Here is the current input loop:
BufferedReader input = new BufferedReader(new InputStreamReader(serverConnection.getInputStream()));
if(input.ready()){
StringBuilder text = new StringBuilder();
String line;
while((line = input.readLine()) != null){
text.append(line);
System.out.println(line);
}
sentData = text.toString();
return true;
}
My current loop using a BufferedReader cannot read more than one line of incoming data, and if there is no newline character, a timeout exception is thrown (I programmed it to do that), and the data is not read at all. It is, of course, unacceptable to have a listener that can only see one line of data, and stalls when the sent data is not formatted properly.
So I am looking for a method that allows the program to read any number of lines, and for the program to stop reading when it has reached the end of the data stream (even without a new line).
Any help is appreciated.
You're throwing away every odd-numbered line. Remove the readLine() inside the loop.
You can read from the InputStream directly into the StringBuilder. readLine() of BufferedReader will wait for \r or \n character. This looks like stalling.
int ch;
StringBuilder text = new StringBuilder();
while((ch = serverConnection.getInputStream().read())!= -1) { // -1 will be read at EOS
text.append((char)ch);
}
sentData = text.toString();
return true;
Update
The following piece of code is to demonstrate the difference between usage of BufferedReader and InputStream to read bytes and what is available to the user during read operation. BufferedReader will always give you lines which are either terminated by line breaks or by EOS. Whereas InputStream will make the available bytes to the user.
In scenarios where it is NOT necessary to close the streams, and the bytes transferred has it's own way to mark start and end of packets/messages, you will be using InputStream to read bytes. If you try using BufferedReader for these applications, the last line of the message will be made available once the server receives the next packet/message, unless you send each line with a line-break.
public static void main(String[] args) throws Exception {
new Thread(new BufferedReaderServer()).start();
new Thread(new InputStreamServer()).start();
final String requestString = "Line#1\nLine#2";
System.out.println("\nSending to BufferedReaderServer");
Socket clientSocket1 = new Socket(InetAddress.getLocalHost()
.getHostAddress(), 8003);
OutputStream outputStream1 = clientSocket1.getOutputStream();
outputStream1.write(requestString.getBytes());
Thread.sleep(6000);
outputStream1.close();
clientSocket1.close();
Thread.sleep(1000);
System.out.println("\nSending to InputStreamServer");
Socket clientSocket2 = new Socket(InetAddress.getLocalHost()
.getHostAddress(), 8004);
OutputStream outputStream2 = clientSocket2.getOutputStream();
outputStream2.write(requestString.getBytes());
Thread.sleep(6000);
outputStream2.close();
clientSocket2.close();
}
static class BufferedReaderServer implements Runnable {
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8003);
Socket socket = serverSocket.accept();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String s = null;
System.out.println("BufferedReaderServer read START");
while ((s = bufferedReader.readLine()) != null) {
System.out.println(s);
}
System.out.println("BufferedReaderServer read END");
socket.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
static class InputStreamServer implements Runnable {
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8004);
Socket socket = serverSocket.accept();
System.out.println("InputStreamServer read START");
int ch;
while ((ch = socket.getInputStream().read()) != -1) {
System.out.print((char) ch);
}
System.out.println("\nInputStreamServer read END");
socket.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The issue what is being faced here could be due to non-closing of client socket. Depends on the user's application

telnet connection inputstream blocking why?

package burak;
import java.io.*;
public class telcon {
public static void main(String[] args) {
try {
String[] command=new String[2];
command[0]="cmd /c start cmd.exe /k \"telnet\"";
command[1]="92.44.0.60";
Process p =Runtime.getRuntime().exec(command);
try {
p.waitFor();
} catch (InterruptedException e) {
System.out.println(e);
}
BufferedReader reader= new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=null;
line=reader.readLine();
File file =new File("rapor.txt");
file.createNewFile();
FileWriter writer=new FileWriter(file);
StringBuilder responseData=new StringBuilder();
while(line!=null) {
System.out.println(line);
responseData.append(line);
writer.write(line);
writer.close();
}
BufferedReader stdInput=new BufferedReader(new InputStreamReader(p.getInputStream()) );
BufferedReader stdError=new BufferedReader(new InputStreamReader(p.getErrorStream()));
String Error;
while((Error=stdError.readLine())!=null) {
System.out.println(Error);
}
while((Error=stdInput.readLine())!=null) {
System.out.println(Error);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
i want to run telnet execute some commands i have two problem first when i connect to telnet it ask me username and password how ı contineude execute commands by using code after the enter password and my second question inputstream is not working readline is empty all time how can ı fix this problems.thanks for hel
I recommend you the Apache Commons Net Java library (http://commons.apache.org/proper/commons-net/) which contains various clients for many Internet protocols, including Telnet. I don't recommend you to use the embedded telnet client from the OS. Things will be cleaner with a library.
In addtion, in your first while loop, you're closing the writer object every iterations, and you don't read further with your reader.

readln of InputStreamReader doesn't work

I have to send and receive with server some stream using java.
The protocol is telnet and if I use cmd in windows with this commands:"telnet 10.0.1.5 9100" and after "^AI202" I have a response.
The code java:
import java.io.*;
import java.net.*;
public static void main(String[] args) throws SocketException, IOException {
Socket s = new Socket();
PrintWriter s_out = null;
BufferedReader s_in = null;
String remoteip = "10.0.1.5";
int remoteport = 9100;
s.connect(new InetSocketAddress(remoteip , remoteport));
s_out = new PrintWriter( s.getOutputStream(), true);
s_in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String message = "^AI202";
try{
System.out.println(s_in.readLine());
}
catch(Error e){
System.out.println(e);
}
s_out.close();
s_in.close();
s.close();
}
The problem is the same: s_in call method readLine() and program cycle infinite.
I think System.out.println(s_in.readLine()); will try to read it over and over again, failing each time and causing infinite loop.
Try
String line ="";
while ((line = s_in.readLine()) != null) {
// Do what you want to do with line.
}
Java Socket BufferReader.readline get null
The problem is that the telnet protocol does not terminate commands with line breaks.
Change your read block to
try {
char [] cbuf = new char[7];
System.out.println(s_in.read(cbuf, 0, cbuf.length));
} catch(Error e){
System.out.println(e);
}
And you will get some input.

Ping value in java

I know that this question has been approached under different ways, but I have checked stackoverflow and I didn't found the answer I was looking for.
To make it simple : Is there a way to get the Time ping value to an IP server under Windows ?
I know how to check if some servers are reachable, but I would like to have precise values, like we can read on terminal.
Thank you for your help and understanding.
You can do something like this :
//The command to execute
String pingCmd = "ping " + ip + " -t";
//get the runtime to execute the command
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(pingCmd);
//Gets the inputstream to read the output of the command
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
//reads the outputs
String inputLine = in.readLine();
while ((inputLine != null)) {
if (inputLine.length() > 0) {
........
}
inputLine = in.readLine();
}
reference
UPDATE: As per your need
public class PingDemo {
public static void main(String[] args) {
String ip = "localhost";
String time = "";
//The command to execute
String pingCmd = "ping " + ip;
//get the runtime to execute the command
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec(pingCmd);
//Gets the inputstream to read the output of the command
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
//reads the outputs
String inputLine = in.readLine();
while ((inputLine != null)) {
if (inputLine.length() > 0 && inputLine.contains("time")) {
time = inputLine.substring(inputLine.indexOf("time"));
break;
}
inputLine = in.readLine();
}
System.out.println("time --> " + time);
} catch (Exception ex) {
System.out.println(ex);
}
}
}
Written in little haste.
You can invoke the ping command and read the output (as explained in the previous answer), or if you need a lower lever access (like you can do with RAW sockets), you can have a look at the jpcap java library.
As shown here, you'll want to make use of the Runtime class to shell out a ping. All that's required of you is to parse the input stream (possibly using regex to get the time ping value).
public static void main(String[] args) {
System.out.println("Enter the host to be pinged : ");
Scanner sc = new Scanner(in);
String str = sc.next();
System.out.println("Enter the no. of packets to be sent : ");
int packets = sc.nextByte();
String pingResult;
int count=0;
try{
String command = "ping -c "+ packets +" -w 10 " + str;
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
if(count==packets+4) {
pingResult = (inputLine.substring(inputLine.indexOf("=")));
pingResult = (pingResult.substring
(pingResult.indexOf("/")+1,pingResult.indexOf("/")+7));
System.out.println(pingResult + " ms");
}
count++;
}
in.close();
if(count==0)System.out.println("Wrong host entered.");
}catch(Exception e){
System.out.println("Exception caught: " + e.toString());
}
}
}
Output:
Enter the host to be pinged :
8.8.8.8
Enter the no. of packets to be sent :
5
31.406 ms
Process finished with exit code 0

Categories

Resources