下面我利用UDP ICMP端口不能到达扫描的原理给出一个完整的例子
import java.net.*;
import java.io.*;
public class socketChecker implements Runnable{
file://declarations
private String server;
private DatagramSocket dsock;
private DatagramPacket packet;
private int port;
private Socket socket;
private String response="";
private BufferedReader is;
private PrintWriter os;
public static final int TCP=0;
public static final int UDP=1;
private int type;
private boolean tcp; // if tcp true, then a tcp scan is done. if false,
udp.
private String message;
private boolean error=false;
// constructor - this is used by the factory method. You should not call
it.
public socketChecker(String server, int port, int type, String message) {
socket=null;
dsock=null;
packet=null;
this.server=server;
this.port=port;
this.type=type;
this.message=message;
response="trying; no connection"; // default response reports message
// if there is a problem connecting it will be caught as
// an exception in the run method...
}
// methods
/* This static factory method is what you use to scan a port
public static String checkSocket(String ahost, int aport,
int timeout, int type, String message);
ahost - the machine to scan
aport - the port to scan
timeout - tells the thread how many milliseconds to wait for the socket
to respond...
int type - you can use the static ints socketChecker.TCP or
socketChecker.UDP to choose tcp or udp scans...
message - a String used either to message a port (TCP), or as
the data for the UDP packet.
(use depends upon "type" of scan selected in type)
*/
public static String checkSocket(String ahost, int aport,
int timeout, int type, String message) {
socketChecker look= new socketChecker(ahost, aport, type, message);
Thread t = new Thread(look);
t.start();
try {
t.join(timeout);
} catch (InterruptedException e) {
System.out.println("InterruptedException e: " + e.toString());
}
return look.getResponse();
}
// getResponse simply returns the String response
private String getResponse() {
return response;
}
// the run method
public void run() {
if (type==TCP) {
tcp=true;
} else {
tcp=false;
}
if (tcp) {
response="trying TCP=/"" + message + "/"; no connection";
// open a tcp socket
try {
socket = new Socket(server, port);
} catch (Exception e) { // catches mainly security and unknown host
exceptions
response+="; " + e.toString();
error=true;
}
if (!error) { // if the socket is open Reader and Writer
try {
is= new BufferedReader(
new InputStreamReader(socket.getInputStream())
);
os= new PrintWriter(
socket.getOutputStream(),true /* autoFlush */
);
} catch (IOException e) {
response+="; IO problem; " + e.toString();
error=true;
}
if (!error) { // if Reader and Writer are open
response="sending TCP=/"" + message + "/"; no reply";
try {
os.println(message);
} catch (Exception e) {
response+=("; "+e.toString()+"="+message);
}
try {
response="sending TCP=/"" + message + "/"; reply="+is.readLine();
} catch (IOException e) {
response+="; " + e.toString();
}
}
}
} else {
// open a udp socket, send a packet, get response..
response="trying UDP packet=/"" + message + "/"; can't create";
try {
dsock=new DatagramSocket();
} catch (SocketException se) {
response="SocketException: " + se.toString();
error=true;
} catch (Exception e) { // mostly to gather the variety of possible
security exceptions
response+="; " + e.toString();
error=true;
}
if (!error) {
response="sending UDP packet=/"" + message + "/"; can't send";
try {
dsock.send(new DatagramPacket(message.getBytes(),
message.getBytes().length,
InetAddress.getByName(server),
port)
);
} catch (UnknownHostException e) {
response+="UnknownHostException:" + e.toString();
error=true;
} catch (IOException e) {
response+="IOException: " + e.toString();
error=true;
} catch (Exception e) { // mostly to gather the variety of possible
security exceptions
response+="; " + e.toString();
error=true;
}
if (!error) {
response="UDP packet sent=/"" + message
+ "/"; no reply";
byte[] buf= new byte[1024];
packet= new DatagramPacket(buf, buf.length);
try {
dsock.receive(packet);
error=true;
} catch (ArrayIndexOutOfBoundsException e) {
response="server trying to overflow buffer: " + e.toString();
error=true;
} catch (IOException e) {
response="IOException: " + e.toString();
error=true;
}
response= "UDP packet sent=/"" + message + "/"; reply=" + new
String(packet.getData(), 0, packet.getLength());
}
}
}
}
}
以上这个例子包括测试tcp和udp端口,下面我会给出一个更简单的例子和测试结果,旨在给大家一个直观的认识,这个例子是充分利用DatagramSocket在本机 bind端口后的会返回SocketException异常的原理做的例子
package com.bw.module.subsystem.bwwms;
import java.net.*;
public class test
{
public static void main(String args[])
{
for (int port=1024;port<=65535;port++) {
try {
DatagramSocket server=new DatagramSocket(port);
server.close();
}
catch(SocketException e) {
System.out.println("there is a server in port "+port+".");
}
}
}
}
测试结果:
there is a server in port 1025.
there is a server in port 1038.
there is a server in port 1058.
there is a server in port 1105.
there is a server in port 1106.
there is a server in port 1147.
there is a server in port 1478.
there is a server in port 1569.
there is a server in port 4000.
there is a server in port 4500.
there is a server in port 6000.
there is a server in port 6001.
there is a server in port 6002.
there is a server in port 6003.
there is a server in port 6004.
there is a server in port 6005.
there is a server in port 6006.
there is a server in port 6007.
there is a server in port 6008.
there is a server in port 6009.
there is a server in port 6010.
there is a server in port 6011.
there is a server in port 6012.
更加详细的用法你可以去认真阅读java.net包然后熟练使用,在此我只是给个抛砖引玉的作用,如果哪位有更好的方法,可以直接联系我,我的email:[email protected]
补上测试远程服务器的测试例子,不过我在这里需要说明的是因为udp协议是属于不可靠协议,所以这里的测试用例我都是在局域网测试成功的,而在现实网络中,有很多网关以及其他一些不可测的原因,所以这个成功率是不能保障的。所以这个示例更适合于要扫描局域网某机udp端口的时候。
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpPort {
public UdpPort() {
super();
// TODO Auto-generated constructor stub
}
public void TestUdpPort()
{
String ipAddress = "192.168.0.29";
int port = 4545;
DatagramSocket connection = null;
byte[] myByte = ipAddress.getBytes();
String myStr = new String(myByte);
try
{
//connection = new DatagramSocket(port, InetAddress.getByName(ipAddress));//(ipAddress, port);
connection = new DatagramSocket();//(ipAddress, port);
//connection.setReceiveTimeout(20*1000);
connection.setSoTimeout(120*1000);
connection.connect( InetAddress.getByName(ipAddress), port);
System.out.println("连结创建完成...");
connection.send((new DatagramPacket(myByte, myByte.length)));
System.out.println(" 数据发送完成...");
while(true)
{
byte[] newByte = new byte[4096];
DatagramPacket dp = new DatagramPacket(newByte, 4096);
connection.receive(dp);
if (dp != null && dp.getData() != null)
{
System.out.println(dp.getLength());
System.out.println("#####");
byte[] rslt = dp.getData();
for (int i = 0;i < dp.getLength(); i++)
{
System.out.println(rslt[i]);
//System.out.println();
}
System.out.println("#####");
}
//String myDump = buffer.getHexDump();
break;
}
connection.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
UdpPort up = new UdpPort();
up.TestUdpPort();
}