I am building a ToyVPN based application to capture tcp / udp packets. After I receive outgoing packets in my application, I would like to forward them to the original destination. I managed to get the destination IP address and port from the headers, but I have no idea how to contact the remote server, and then write the response back to the source. I think this is possible because there is an 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());
ByteBuffer packet = ByteBuffer.allocate(32767);
boolean ok = true;
while (ok) {
Socket tcpSocket = SocketChannel.open().socket();
try {
int length = in.read(packet.array());
if (length > 0) {
Log.i(TAG, "-------------------New packet: " + length);
packet.limit(length);
InetAddress serverAddr = InetAddress.getByName(destIP);
SocketAddress socketadd = new InetSocketAddress(serverAddr,
destPort);
protect(tcpSocket);
OutputStream outBuffer = tcpSocket.getOutputStream();
outBuffer.write(packet.array());
outBuffer.flush();
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();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, e.toString());
ok = false;
}
tcpSocket.close();
}
in.close();
out.close();
}
source
share