问题
I'm creating application based on ToyVPN to capture tcp/udp packets. After i get outgoing packets in my apllication i would like to forward them to original destination. I have managed to get destination ip and port from headers but i have no idea how to communicate with remote server and then write response back to the source. I think this is possible because there is this app. Here is my first first attempt:
private void runVpnConnection() throws Exception {
configure();
FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
FileOutputStream out = new FileOutputStream(
mInterface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(32767);
boolean ok = true;
while (ok) {
Socket tcpSocket = SocketChannel.open().socket();
try {
// Read the outgoing packet from the input stream.
int length = in.read(packet.array());
if (length > 0) {
Log.i(TAG, "-------------------New packet: " + length);
packet.limit(length);
// here i get destIP and destIP
InetAddress serverAddr = InetAddress.getByName(destIP);
SocketAddress socketadd = new InetSocketAddress(serverAddr,
destPort);
protect(tcpSocket);
OutputStream outBuffer = tcpSocket.getOutputStream();
outBuffer.write(packet.array());
outBuffer.flush();
// outBuffer.close();
packet.clear();
}
if (tcpSocket.isConnected()) {
InputStream inBuffer = tcpSocket.getInputStream();
DataInputStream inStream = new DataInputStream(inBuffer);
Log.i(TAG, "Response length " + inStream.available());
if (inStream.available() > 0) {
Log.i(TAG, "Server says " + inStream.readUTF());
inStream.readFully(packet.array());
out.write(packet.array());
inBuffer.close();
}
out.flush();
}
packet.clear();
// Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, e.toString());
ok = false;
}
tcpSocket.close();
}
in.close();
out.close();
}
回答1:
Apparently tPacketCapture routes the traffice into another interface running on the phone and sends all of this traffic to the internet (this is the same as mobiwol, greyshirts and other apps that use VPNService).
If you run (and understand) ToyVPN, you know that all of the traffic from the phone goes into a server (your computer) in which you configure iptables to send all the traffic to the internet.
If you want to run without a server, yo have to do the same thing on the phone. From another question:
When I look at mobiwol's connection with "adb shell netcfg" it creates a tun0 interface with 10.2.3.4/32 address. It routes all packages to this private network and send to internet.
So basically from your app you will have to configure the phone to act as it's own server.
来源:https://stackoverflow.com/questions/21910082/android-vpnservice-packets-forwarding