我有一个nginx反向代理服务器监听
0.0.0.0
,server_name为feng.cc:8080
,部分配置如下:
upstream ssl-proxy {
server 172.16.43.210:5000;
}
server {
listen 0.0.0.0:8080;
server_name feng.cc:8080;
location / {
proxy_pass http://ssl-proxy/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header Connection "";
}
}
nginx服务器的静态IP是
172.16.39.52
,feng.cc
是自定义域名映射到hosts文件中的静态IP。
我有用C编写的nginx模块,但我不知道如何获取模块中的静态IP。
我发现
ngx_http_request_s
结构中有一些数据成员,例如r->connection->local_sockaddr
和r->connection->listening
,
但这些给了我0.0.0.0
而不是静态IP。
我还发现nginx服务器通过静态IP与上游服务器通信:
$ hostname -I
172.16.39.52
$ tcpdump -nn -iany dst port 5000
eth0 Out IP 172.16.39.52.26130 > 172.16.43.210.5000: Flags [S], seq 3565149610, win 32120, options [mss 1460,sackOK,TS val 1811543954 ecr 0,nop,wscale 7], length 0
eth0 Out IP 172.16.39.52.26130 > 172.16.43.210.5000: Flags [.], ack 515140155, win 251, options [nop,nop,TS val 1811543955 ecr 2228136305], length 0
eth0 Out IP 172.16.39.52.26130 > 172.16.43.210.5000: Flags [P.], seq 0:139, ack 1, win 251, options [nop,nop,TS val 1811543955 ecr 2228136305], length 139
eth0 Out IP 172.16.39.52.26130 > 172.16.43.210.5000: Flags [.], ack 174, win 250, options [nop,nop,TS val 1811543957 ecr 2228136307], length 0
eth0 Out IP 172.16.39.52.26130 > 172.16.43.210.5000: Flags [.], ack 203, win 250, options [nop,nop,TS val 1811543957 ecr 2228136307], length 0
eth0 Out IP 172.16.39.52.26130 > 172.16.43.210.5000: Flags [F.], seq 139, ack 203, win 250, options [nop,nop,TS val 1811543958 ecr 2228136307], length 0
eth0 Out IP 172.16.39.52.26130 > 172.16.43.210.5000: Flags [.], ack 204, win 250, options [nop,nop,TS val 1811543959 ecr 2228136309], length 0
有没有办法用C编程获取nginx服务器的静态IP?
遗憾的是,我收到了两票否决票,也许我的描述不清楚,或者问题本身不适合放在这里。
无论如何,我终于找到了使用
socket fd
获取nginx服务器IPv4地址的解决方案:
char server_ip[INET_ADDRSTRLEN];
struct sockaddr_in laddr;
socklen_t laddr_len = sizeof(laddr);
if (getsockname(r->connection->fd, (struct sockaddr*)&laddr, &laddr_len) == 0) {
inet_ntop(AF_INET, &laddr.sin_addr, server_ip, sizeof(server_ip));
}