[英]binding socket to specific interface
I am trying to bind a socket to the specific (loopback) interface lo
to prevent outside traffic from interfering with it: 我正在尝试将套接字绑定到特定的(环回)接口lo
以防止外部流量对其干扰:
int bind_socket(uint8_t *iface, uint8_t port) {
int rv;
struct sockaddr_in addr;
rv = socket(AF_INET, SOCK_STREAM, 0);
if (rv < 0) return -1;
if (setsockopt(rv, SOL_SOCKET, SO_BINDTODEVICE, iface, strlen(iface)) < 0) {
return -2;
}
bzero((char *) &addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(port);
if (bind(rv, (struct sockaddr *) &addr, sizeof(addr)) < 0)
return -3;
return rv;
}
...
int ss;
ss = bind_socket("lo", 100);
However, if I run nmap localhost -e wlpXsX
, I should not be getting output indicating the socket is available through that interface. 但是,如果运行nmap localhost -e wlpXsX
,则不应获得指示套接字可通过该接口使用的输出。 It is instead being reported as available; 相反,它被报告为可用。 and I can't seem to be able to deduce why. 而且我似乎无法推断出原因。 Why is this interface globally available with a program designed to make it unavailable to all other interfaces? 为什么此接口在全球范围内都可以使用设计为使其对所有其他接口均不可用的程序可用?
You wrote: 你写了:
I am trying to bind a socket to the specific (loopback) interface 我正在尝试将套接字绑定到特定的(环回)接口
but you coded: 但是你编码:
addr.sin_addr.s_addr = INADDR_ANY;
INADDR_ANY
(0.0.0.0) is not the loopback interface. INADDR_ANY
(0.0.0.0) 不是回送接口。 You need to change it to INADDR_LOOPBACK
(127.0.0.1) instead: 您需要将其更改为INADDR_LOOPBACK
(127.0.0.1):
addr.sin_addr.s_addr = htons(INADDR_LOOPBACK);
It seems nmap
was ignoring the interface switch, and routing its probes through the loopback interface anyway. nmap
似乎忽略了接口开关,无论如何都通过环回接口路由其探针。 Passing my LAN address as the target instead of localhost
, and my LAN interface as the interface argument to nmap
produced the intended result of the socket being invisible to outside the local host with the following source code: 将我的LAN地址作为目标而不是localhost
传递,并将我的LAN接口作为nmap
的接口参数传递时,使用以下源代码可以使套接字对本地主机外部不可见,从而达到预期的效果:
int bind_lo(int port) {
int rv;
const char iface[] = "lo";
struct sockaddr_in addr;
rv = socket(AF_INET, SOCK_STREAM, 0);
if (rv < 0) return -1;
bzero((char *) &addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(port);
if (bind(rv, (struct sockaddr *) &addr, sizeof(addr)) < 0)
return -2;
if (setsockopt(rv, SOL_SOCKET, SO_BINDTODEVICE, iface, strlen(iface) + 1) < 0) {
return -3;
}
return rv;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.