I need to establish vpn tunnelin using ssh connection in android kotlin. currently i’m able to connect to ssh server using JSch library and forward local port and establish vpn service , but unfortunately i have no access to internet after that. (I tested my ssh connection using another app and it works , so there is nothing with server)
Here is my snippet code :
val jsch = JSch()
val session: Session = jsch.getSession("test", sshAddress, sshPort)
session.setPassword(sshPassword)
session.setConfig("StrictHostKeyChecking", "no")
session.connect()
println("jsch connected")
// Create port forwarding
val assignedPort: Int =
session.setPortForwardingL(8180, sshAddress, sshPort)
println("assignedPort : $assignedPort")
and vpn builder :
val builder: Builder = Builder()
builder.addAddress("10.0.0.2", 32)
builder.addRoute("0.0.0.0", 0)
builder.addDisallowedApplication("com.example.x")
mInterface = builder.setSession("MyVPN")
.establish()
println("vpn established")
// Create a DatagramChannel to handle VPN packets
val vpnChannel = DatagramChannel.open()
vpnChannel.connect(InetSocketAddress(sshAddress, 7300))
// Allocate buffer for a single packet
val packet = ByteBuffer.allocate(32767)
// Get file descriptors for VPN interface
val vpnInput = FileInputStream(mInterface!!.fileDescriptor)
// Start forwarding packets
// Start forwarding packets
while (!Thread.interrupted()) {
// Read packet from VPN interface
val length = vpnInput.read(packet.array())
if (length > 0) {
// Set the buffer position to the length of the received packet
packet.position(length)
// Write packet to SSH tunnel
packet.flip() // Prepare the buffer for writing
vpnChannel.write(packet)
// Clear and reset the buffer for next packet
packet.clear()
} else if (length < 0) {
// End of stream reached, break out of the loop
break
}
}