为什么不能将linux服务仅绑定到环回?
我正在编写一个服务器应用程序,它将在临时端口上提供服务,我只想在环回接口上访问该服务。为了做到这一点,我编写如下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应该避免使用inet_addr,因为有一种更明智的构造struct sockaddr的方法(这意味着它也废弃了gethostby*):
inet_addr
should be avoided, for there is a much saner method of constructingstruct sockaddr
s (which means it also obsoletesgethostby*
):吗?
因此删除 htonl 调用。
Yes.
So remove the htonl call.