为什么不能将linux服务仅绑定到环回?

发布于 2024-10-11 03:07:14 字数 486 浏览 3 评论 0原文

我正在编写一个服务器应用程序,它将在临时端口上提供服务,我只想在环回接口上访问该服务。为了做到这一点,我编写如下代码:

struct sockaddr_in bind_addr;

memset(&bind_addr,0,sizeof(bind_addr));
bind_addr.sin_family = AF_INET;
bind_addr.sin_port = 0;
bind_addr.sin_addr.s_addr = htonl(inet_addr("127.0.0.1"));
rcd = ::bind(
   socket_handle,
   reinterpret_cast<struct sockaddr *>(&bind_addr),
   sizeof(bind_addr));

对bind()的调用的返回值为-1,errno的值为99(无法分配请求的地址)。失败是因为 inet_addr() 已经按网络顺序返回其结果还是有其他原因?

I am writing a server application that will provide a service on an ephemeral port that I only want accessible on the loopback interface. In order to do this, I am writing code like the following:

struct sockaddr_in bind_addr;

memset(&bind_addr,0,sizeof(bind_addr));
bind_addr.sin_family = AF_INET;
bind_addr.sin_port = 0;
bind_addr.sin_addr.s_addr = htonl(inet_addr("127.0.0.1"));
rcd = ::bind(
   socket_handle,
   reinterpret_cast<struct sockaddr *>(&bind_addr),
   sizeof(bind_addr));

The return value for this call to bind() is -1 and the value of errno is 99 (Cannot assign requested address). Is this failing because inet_addr() already returns its result in network order or is there some other reason?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最美的太阳 2024-10-18 03:07:14

应该避免使用inet_addr,因为有一种更明智的构造struct sockaddr的方法(这意味着它也废弃了gethostby*):

#include <netdb.h>

/* Error checking omitted for brevity */
struct addrinfo hints = {.ai_flags = AI_PASSIVE};
struct addrinfo *res;
getaddrinfo("::1", NULL, &hints, &res); /* or 127.0.0.1 if you are 60+ */
bind(fd, res->ai_addr, res->ai_addrlen);
freeaddrinfo(res);

inet_addr should be avoided, for there is a much saner method of constructing struct sockaddrs (which means it also obsoletes gethostby*):

#include <netdb.h>

/* Error checking omitted for brevity */
struct addrinfo hints = {.ai_flags = AI_PASSIVE};
struct addrinfo *res;
getaddrinfo("::1", NULL, &hints, &res); /* or 127.0.0.1 if you are 60+ */
bind(fd, res->ai_addr, res->ai_addrlen);
freeaddrinfo(res);
春花秋月 2024-10-18 03:07:14

这是因为 inet_addr() 已经按网络顺序返回其结果而失败吗

吗?

因此删除 htonl 调用。

Is this failing because inet_addr() already returns its result in network order

Yes.

So remove the htonl call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文