根据input_ip & net_mask == seted_ip & net_mask 来判断。
详见代码:
1 typedef struct { 2 ngx_uint_t ip[4]; 3 ngx_uint_t mask[4]; 4 } ngx_stream_eth_netSegment_t; 5 6 7 typedef struct { 8 ngx_array_t eths; // ngx_streams_eth_srv_conf_t 9 } ngx_streams_eth_main_conf_t; 10 11 12 typedef struct { 13 ngx_str_t ethname; 14 ngx_array_t netSegments; // ngx_stream_eth_netSegment_t 15 } ngx_streams_eth_srv_conf_t ;
1 static ngx_int_t 2 ngx_streams_eth_ip_atoi(ngx_str_t *ip, ngx_uint_t iparr[]) 3 { 4 int i=0, j; 5 u_char *p, tmp[4]={0}; 6 int cnt=0; 7 ngx_int_t len; 8 9 p = ip->data; 10 len = ip->len; 11 12 for (j=0; j < len; j++) { 13 if (*p == '.' || j == len - 1) { 14 if (j == len -1) { 15 tmp[cnt++] = *p; 16 } 17 iparr[i++] = ngx_atoi(tmp, cnt); 18 ngx_memset(tmp, 0, sizeof(tmp)); 19 cnt = 0; 20 p++; 21 continue; 22 } 23 tmp[cnt++] = *p++; 24 if (cnt > 3) { 25 return NGX_ERROR; 26 } 27 } 28 29 30 return NGX_OK; 31 } 32 33 34 static ngx_int_t 35 ngx_streams_eth_is_same_net(ngx_str_t *ip, ngx_stream_eth_netSegment_t *netSegment) 36 { 37 ngx_uint_t iparr[4]={0}; 38 ngx_int_t i; 39 if (ngx_streams_eth_ip_atoi(ip, iparr) != NGX_OK) { 40 return NGX_ERROR; 41 } 42 43 for (i=0; i<4; i++) { 44 if ((iparr[i] & netSegment->mask[i]) != 45 (netSegment->ip[i] & netSegment->mask[i]) ) { 46 return NGX_ERROR; 47 } 48 } 49 return NGX_OK; 50 } 51 52 53 ngx_stream_eth_netSegment_t * 54 ngx_streams_eth_match(ngx_str_t *ip) { 55 ngx_streams_eth_main_conf_t *smcf; 56 ngx_int_t i, j; 57 ngx_streams_eth_srv_conf_t *sscf; 58 ngx_stream_eth_netSegment_t *netSegment; 59 60 smcf = ngx_streams_cycle_get_module_main_conf(ngx_cycle, ngx_streams_eth_module); 61 for (i = 0; i < smcf->eths.nelts; i++) { 62 sscf = ngx_array_pop(&smcf->eths, i); 63 if (sscf == NULL) { 64 goto failed; 65 } 66 for (j = 0; j < sscf->netSegments.nelts; j++) { 67 netSegment = ngx_array_pop(&sscf->netSegments, j); 68 if (ngx_streams_eth_is_same_net(ip, netSegment) == NGX_OK) { 69 return netSegment; 70 } 71 } 72 } 73 74 failed: 75 return NULL; 76 }
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:nginx中判断输入ip是否和配置ip在同一个网段 - Python技术站