Commit bccd05d2 authored by nanamicat's avatar nanamicat

init

parents
# Project exclude paths
/cmake-build-debug/
/.idea/
\ No newline at end of file
cmake_minimum_required(VERSION 3.22)
project(tun)
set(CMAKE_CXX_STANDARD 23)
add_executable(tun main.cpp)
find_package(Threads REQUIRED)
target_link_libraries(tun Threads::Threads)
#target_link_libraries(tun fmt)
#include <iostream>
#include <thread>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <linux/if.h>
#include <linux/if_tun.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <arpa/inet.h>
// internet -> tun
void inbound(int raw, int tun) {
char buf[ETH_DATA_LEN];
sockaddr_in addr{AF_INET};
size_t nread;
while ((nread = recvfrom(raw, buf, sizeof(buf), 0, (sockaddr *)&addr, nullptr)) >= 0) {
if (write(tun, buf, nread) < 0) {
perror("outbound write");
}
}
perror("outbound read");
}
in_addr_t remote;
// tun -> internet
void outbound(int raw, int tun) {
char buf[ETH_DATA_LEN];
sockaddr_in addr{AF_INET};
addr.sin_addr.s_addr = remote;
size_t nread;
while ((nread = read(tun, buf, sizeof(buf))) >= 0) {
if (sendto(raw, buf, nread, 0, (sockaddr *) &addr, sizeof(addr)) < 0) {
perror("inbound write");
}
}
perror("inbound read");
}
int main(int argc, char* argv[]) {
ifreq ifr{};
ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
auto raw = socket(AF_INET, SOCK_RAW, IPPROTO_IPIP);
auto tun = open("/dev/net/tun", O_RDWR);
ioctl(tun, TUNSETIFF, &ifr);
remote = inet_addr(argv[1]);
std::cout << raw << std::endl;
std::cout << tun << std::endl;
std::thread t1(inbound, raw, tun);
std::thread t2(outbound, raw, tun);
t1.join();
t2.join();
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment