端口转发

各平台端口转发方法

Windows

主要是使用 netsh 接口进行管理.

添加示例

1
netsh interface portproxy add v4tov4 listenaddress=addr listenport=port connectaddress=addr2 connectport=port2

其他选项

  • netsh interface portproxy dump
  • …show all
  • …delete v4tov4 listenaddress=addr listenport=port
  • …reset

Linux

使用 firewall-cmd

1
2
3
4
5
6
7
8
9
10
11
# Enable masquerading
$ sudo firewall-cmd --add-masquerade --permanent

# Port forward to a different port within same server ( 22 > 2022)
$ sudo firewall-cmd --add-forward-port=port=22:proto=tcp:toport=2022 --permanent

# Port forward to same port on a different server (local:22 > 192.168.2.10:22)
$ sudo firewall-cmd --add-forward-port=port=22:proto=tcp:toaddr=192.168.2.10 --permanent

# Port forward to different port on a different server (local:7071 > 10.50.142.37:9071)
$ sudo firewall-cmd --add-forward-port=port=7071:proto=tcp:toport=9071:toaddr=10.50.142.37 --permanent

使用 iptables

nat-HOWTO

1
2
3
4
5
6
7
8
cat /proc/sys/net/ipv4/conf/ppp0/forwarding
cat /proc/sys/net/ipv4/conf/eth0/forwarding

echo '1' | sudo tee /proc/sys/net/ipv4/conf/ppp0/forwarding
echo '1' | sudo tee /proc/sys/net/ipv4/conf/eth0/forwarding

iptables -t nat -A PREROUTING -p tcp -i ppp0 --dport 8001 -j DNAT --to-destination 192.168.1.200:8080
iptables -A FORWARD -p tcp -d 192.168.1.200 --dport 8080 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

fPIC和fpic及fPIE和fpie的说明

概念

-fPIC/-fpic: 针对编译生成动态库。

-fPIE/-fpie:针对生成可执行文件。

-fPIC/-fpic :编译选项,用于生成位置无关的代码 **(Position-Independent-Code)**,代码在加载到内存时使用相对地址,所有对固定地址的访问都通过全局偏移表 (GOT) 来实现。

-fPIC 对偏移表的大小有限制,-fpic 对便移表没有大小限制;在未知情况下,用 -fPIC

-fPIE/-fpie:编译选项,同 -fPIC/-fpic 相同,作用于生成可执行文件过程。

来源

使用迭代遍历目录

C++ code under Linux

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>
#include <queue>
#include <string>

std::vector<std::string> listDirAndFiles(const std::string& dir) {
DIR * d = NULL;
struct dirent * entry = NULL;

std::vector<std::string> flist;
std::queue<std::string> queue;

queue.push(dir);

while(!queue.empty()) {
auto path = queue.front();
queue.pop();
d = opendir(path.c_str());
if(d == NULL) {
std::cout << "failed to open: " << path << std::endl;
continue;
}

entry = readdir(d);

for(; entry != NULL; entry = readdir(d)) {
if(entry->d_type == DT_DIR) {
if(strcmp(entry->d_name, ".") ==0) continue;
if(strcmp(entry->d_name, "..") ==0) continue;
queue.push(path + "/" + entry->d_name);
}

flist.push_back(path + "/" + entry->d_name);
}

closedir(d);
}

return flist;
}


int main(int argc, char** argv) {
if(argc != 2) return 1;

auto list = listDirAndFiles(argv[1]);
std::cout << "find dir and files: " << list.size() << std::endl;
return 0;
}