原理概述
nginx 运行在端口A,转发数据给端口B,C++ 监听端口B的数据。
本文例子
使用 C++ 和 nginx 获取客户端的IP地址
代码
nginx 配置
- #user nobody;
- worker_processes 1;
- events {
- worker_connections 1024;
- }
- http {
- include mime.types;
- default_type application/octet-stream;
- sendfile on;
- keepalive_timeout 65;
- server {
- listen 2335;
- # 如果用服务器启动nginx, 这里写服务器的地址, 不写 localhost
- # 例如: server_name 1xx.1xx.1xx.1xx
- server_name localhost;
- # 转发 API 请求到 C++ 应用
- location / {
- # 假设 C++ 应用运行在 5033 端口
- proxy_pass http://localhost:5033/;
- # 使用 HTTP/1.1
- proxy_http_version 1.1;
- # 支持 WebSocket
- proxy_set_header Upgrade $http_upgrade;
- proxy_set_header Connection 'upgrade';
- proxy_set_header Host $host;
- proxy_cache_bypass $http_upgrade;
- proxy_set_header X-Real-IP $remote_addr;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- }
- error_page 500 502 503 504 /50x.html;
- location = /50x.html {
- root html;
- }
- }
- }
复制代码 CPP代码
[code]#include #include #include #pragma comment(lib, "ws2_32.lib")using std::cout;using std::endl;using std::string;int main(){ WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { cout |