java使用抓包获得应用发送的对外的请求
java使用jpcap抓包工具获得本机发送的所有tcp请求,根据tcp请求的内容可以调试某个应用启动后对外发送的相关http请求或者sql连接请求,这样可以很好的调试我们的程序。很不错的一种应用无侵入性的调试本机发送的http接口,sql连接接口等。
import java.io.UnsupportedEncodingException; import java.net.InetAddress; import jpcap.*; import jpcap.packet.EthernetPacket; import jpcap.packet.Packet; import jpcap.packet.TCPPacket; class Tcpdump implements PacketReceiver { public void receivePacket(Packet packet) { // System.out.println(packet); if (packet instanceof TCPPacket) { TCPPacket tcpPacket = (TCPPacket) packet; if(tcpPacket.src_ip.getHostAddress().equals(getIp())){ EthernetPacket ethernetPacket = (EthernetPacket) packet.datalink; System.out.print("源IP:" + tcpPacket.src_ip + " 目的IP:" + tcpPacket.dst_ip + "发送端口:" + tcpPacket.src_port + " 接收端口:" + tcpPacket.dst_port + "\n"); System.out .print("源MAC:" + ethernetPacket.getSourceAddress() + " 目的MAC:" + ethernetPacket.getDestinationAddress() + "\n"); System.out.print("协议:" + tcpPacket.protocol + "\n"); System.out.print("数据:\n"); try { System.out.println(new String(tcpPacket.data,"utf-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } // for (int i = 0; i < tcpPacket.data.length; i++) // System.out.print((char) tcpPacket.data[i]); } } } public static String getIp(){ InetAddress inet = null; try { inet = InetAddress.getLocalHost(); String ip = inet.getHostAddress(); //在某些linux机器上取到的ip是host绑定的本机ip,即127.0.0.1 return ip; }catch(Exception e){ } return null; } }<span style="white-space: normal; background-color: #ffffff;"> </span>
我先启动给一个查询数据库的一个应用,然后再启动下面的程序,
输出结果如下: