由于这个非 RFC 标头字段不在 HTTP_Env 或 http_t 结构中,所以我写了这个片段:
//Get reply buffer
xbuf_t *reply = get_reply(argv);
// Init & create json buffer
xbuf_t json_buf;
xbuf_init(&json_buf);
jsn_t *params = jsn_add_node(0, "params");
[...]
http_t *http = (http_t*)get_env(argv, HTTP_HEADERS);
xbuf_t *read_buf = (xbuf_t*)get_env(argv, READ_XBUF);
[...]
// Add remote ip (from X-Forwarded-for or REMOTE_ADDR)
char *xforward = xbuf_findstr(read_buf, "X-Forwarded-For:");
if(xforward) {
jsn_add_string(params, "ip", xforward);
} else {
jsn_add_string(params, "ip", get_env(argv, REMOTE_ADDR));
}
当然,json 部分是应用程序的一部分,与问题无关。您认为这是正确的方法还是 xbuf_findstr() 效率低下并且有更快的解决方案(不使用 ASM 或神秘代码)?
谢谢 :)
编辑:哇,我忘记了 strok() 部分来摆脱第一个字段,我当然只想要 IP 地址。
EDIT2:带有 strtok 的修补版本
// Add remote ip (from X-Forwarded-for or REMOTE_ADDR)
char *xforward = xbuf_findstr(read_buf, "X-Forwarded-For: ");
if(xforward) {
gc_init(argv, 1024);
char *copy = gc_malloc(argv, strlen(xforward)+ 1);
memcpy(copy, xforward, strlen(xforward) + 1);
strtok(copy, ":");
char *ip = strtok(0,"\r");
while (*ip == ' ') ip++; // Trim leading space
jsn_add_string(params, "ip", ip);
} else {
jsn_add_string(params, "ip", get_env(argv, REMOTE_ADDR));
}