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