-1

I am making a small project with Java sockets, it's like a port scanner and I am wondering if I can detect a port "version" like with Zenmap. In case you're not familiar with what I'm talking about, if you scan a target with zenmap then go to "Ports / Hosts" and you get something like this.

I was wondering if I could get the port "version" information in Java.

  • IANA maintains the _[Service Name and Transport Protocol Port Number Registry](https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml)_. – Ron Maupin Jun 13 '20 at 19:16

1 Answers1

1

When you get a connection, try reading the first line the server sends. Many applications identify themselves when the connection is established. This is especially true for ftp servers like your example.

For example, this connects to a port on a server and reads up to 1000 bytes from what the server sent, which should be enough:

Socket s = new Socket(hostname, port)
InputStream in = s.getInputStream();
byte[] bs = new byte[1000];
int len = in.read(bs);
s.close();

You can then convert those bytes into a string:

String serverInfo = new String(bs, 0, len);
// I got "SSH-2.0-OpenSSH_5.3\r\n" in a test

Not all protocols start with the server sending something so you should also set a timeout for reading from the socket.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • How would I go about this? I have tried to research this but with no results. –  Jun 15 '20 at 02:58
  • That is pretty unreliable code. Some servers may send the ident string and also start the underlying protocol with binary data, like SSH. May I suggest to wrap the socket InputStream in a BufferedReader and then just use its readLine method? – President James K. Polk Jun 15 '20 at 15:08
  • @Joni I have an error when I use the code you provided, here is the error: `Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: offset 0, count -1, length 1000` Indicating the string index became a negative number. –  Jun 16 '20 at 01:19
  • Yes to make this "production quality" you need to add checks for conditions such as the server closing the connection before it sends anything (which causes the error you see) or sending binary data instead of readable text, or anything else from a number of possible behaviors – Joni Jun 19 '20 at 02:46