Mac端口转发

1. 问题

Mac 与 linux一样,1024以下端口为特权端口,只有root用户才有权监听。因此,要在mac上使用web服务软件监听80或433端口,要么以root用户启动应用程序,要么使用端口转发。

2. 使用ipfw(Internet Protocol Firewall)设置端口转发

//不过,ipfw工具在高版本mac里面已经不存在了
ipfw add 100 fwd 127.0.0.1,8080 tcp from any to any 80 in

3. 使用pf(packet filter)

1.创建anchor文件

anchor文件定义了我们想要转发的端口。

//文件位置
/etc/pf.anchors/<CUSTOM NAME>
//文件内容,可以添加多行以下格式内容
rdr pass on lo0 inet proto tcp from any to any port <source port> -> 127.0.0.1 port <destination port>
//如:8080 转发到80
//rdr pass on lo0 inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080
2. 测试anchor文件
//测试命令
sudo pfctl -vnf /etc/pf.anchors/<CUSTOM NAME>

这是时候端口转发并未生效,只是检查anchor文件是否合法。如果看到以下输出结果,证明是有效的。

fctl: Use of -f option, could result in flushing of rules
present in the main ruleset added by the system at startup.
See /etc/pf.conf for further details.

rdr pass on lo0 inet proto tcp from any to any port = <SOURCE PORT> -> 127.0.0.1 port <DESTINATION PORT>
3. 创建pfctl config文件

anchor文件验证后,需要创建pfctl config文件。

//文件位置
/etc/pf-<CUSTOM NAME>.conf
//配置内容
rdr-anchor "forwarding"
load anchor "forwarding" from "/etc/pf.anchors/<CUSTOM NAME>"
4. 测试配置文件

可通过以下命令启动,停止pfctl

//启动
sudo pfctl -ef /etc/pf-<CUSTOM NAME>.conf
//停止 
sudo pfctl -df /etc/pf-<CUSTOM NAME>.conf

4. 端口转发启动生效

上面的命令可以根据需求启动和停止端口转发。另外如果想要机器启动自动开启端口转发,可以通过launchctl plist file。

  //文件位置
  /Library/LaunchDaemons/com.apple.pfctl-<CUSTOM NAME>.plist
  //文件内容
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
         <key>Label</key>
         <string>com.apple.pfctl-<CUSTOM NAME></string>
         <key>Program</key>
         <string>/sbin/pfctl</string>
         <key>ProgramArguments</key>
         <array>
              <string>pfctl</string>
              <string>-e</string>
              <string>-f</string>
              <string>/etc/pf-<CUSTOM NAME>.conf</string>
         </array>
         <key>RunAtLoad</key>
         <true/>
         <key>KeepAlive</key>
         <false/>
    </dict>
    </plist>
//添加到启动运行列表
sudo launchctl load -w /Library/LaunchDaemons/com.apple.pfctl-<CUSTOM NAME>.plist
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,973评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,970评论 6 342
  • 文章图片上传不正常,如需文档,可联系微信:1017429387 目录 1 安装... 4 1.1 配置探针... ...
    Mrhappy_a7eb阅读 6,504评论 0 5
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,615评论 8 265
  • 【韩喜文2017.12.06星期三】 好展馆让天下没有卖不出去的产品 好展馆让天下没有不能传承的文化 日精进:7...
    韩喜文阅读 76评论 0 1