telneting ip/port in java/jsp - java

I'm trying to make a script that telnet ip port to see if the server is up or down. (like how you do in window command prompt. cmd [enter] => telnet 11.111.11.11 200 (ip& port)and if the the connection is successful, program will return true else false. I need this code to be really efficient since this function will go into the forloop where I do all the displays on the website for each ip. Thnx in advance
P.S
Ops I meant java/jsp my bad haha

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) {
} catch (IOException e) {
}

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

Android client can't open a socket to a C server

I couldn't find anything about this quite specific problem, but maybe someone else has done this.
I have a server program written in C (error checking removed for readability):
int main(int arc, char *argv[])
{
int sockfd, newsockfd, portnum, cli_len, num_chars, n;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
// Set up the socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
// Set up our variables
bzero((char *) &serv_addr, sizeof(serv_addr));
portnum = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portnum); // Convert from host port to network port
serv_addr.sin_addr.s_addr = INADDR_ANY;
if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("Socket could not be bound");
listen(sockfd, 5); // Get ready to receive connections
cli_len = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &cli_len);
// Message processing
return 0;
}
Meanwhile, I have the Android client (Version 4.1.2):
private class ClientTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
InetAddress a = InetAddress.getByAddress(new byte[] {(byte) 192, (byte) 168, 1, (byte) 102});
sock = new Socket(a, 65053);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
DataOutputStream outToServer = new DataOutputStream(sock.getOutputStream());
// Message processing
} catch (UnknownHostException e) {
System.out.println("No address found for ");
} catch (IOException e) {
System.out.println("Failed to open socket");
}
return null;
}
}
The issue I have is that the socket can't be opened by the Android client. I always get "Failed to open socket" after the timeout. The android client works with a java server I have, and a java client I have at least makes the connection with the C server. I don't understand what could be wrong...
If you need more details or additional code, let me know.
You don't specify if you're running both devices (server and client) just under the same LAN, in which case you can discard connectivity problems. If not, this might be a test. If you're able to connect your client to your server under the same router, that means that otherwise (i.e., using your public IPs) there's something blocking it, probably your router. Another issues could be antiviruses, OS ports blocking, router ports blocking...
If you're not able to connect both either under the same router connection, definitely it's a code issue. As you don't know where the culprit is, I'd suggest putting several Log.d() lines within the client code and printf() statements within the server code in the connectivity snippets on both sides and see where the bottleneck is, or use some debugging tool and put some breakpoints.
---- EDIT ----
Try connecting this way:
Socket socket;
final String host = "192.168.1.X";
final int port = 65053;
final int timeout = 30000; // 30 seconds
try {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout);
}
catch (UnknownHostException uhe) {
Log.e("Sock", "I couldn't resolve the host you've provided!");
}
catch (SocketTimeoutException ste) {
Log.e("Sock", "After a reasonable amount of time, I'm not able to connect!");
}
catch (IOException ioe) {
Log.e("Sock", "Hmmm... Sudden disconnection, probably you should start again!");
}
Whelp, it was a firewall issue, embarrassingly enough. Apparently Eclipse was let through my firewall, which is why the Java server worked, but I must've missed the prompt when I ran my C code through the command line. I disabled my firewall and it worked immediately.

Exception : java.net.BindException: Cannot assign requested address

I want to send and receive datagram socket but I'm getting exception java.net.BindException: Cannot assign requested address. I passed the correct ipaddress of the server which I want to communicate and correct port no.
try {
SocketAddress sockaddr = new InetSocketAddress("203.100.77.54", 8000);
DatagramSocket sock = new DatagramSocket(sockaddr);
DatagramPacket pack = new DatagramPacket(bData, bData.length);
sock.send(pack);
} catch (FileNotFoundException fnfe) {
Log.e(LOG_TAG, "FileNotFoundException");
} catch (SocketException se) {
Log.e(LOG_TAG, "SocketException");
} catch (UnknownHostException uhe) {
Log.e(LOG_TAG, "UnknownHostException");
} catch (IOException ie) {
Log.e(LOG_TAG, "IOException");
}
Please help me.
DatagramSockets aren't created with a target address. They are created with their own local bind-address, or none, which causes a default bind when first used. The target address is specified when constructing the DatagramPacket, or in the connect() method.
try like this
String messageStr = "Hello Android!";
int server_port = 8000;
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName("203.100.77.54");
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
s.send(p);
Here's a more high-level answer:
Direct UDP, like direct TCP, is meant for a specific address, like Bob. So if I'm sending the packets to Bob, then you aren't allowed to listen for them -- you can only listen for yourself. So if you try to open a listener for Bob, your device tells you that you aren't allowed.
Unless you are using multicast UDP or something like that, you can only listen to things that are meant to be sent directly to you, hence the IP or whatever address must be that devices own address.

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