gpt4 book ai didi

c - 了解用于套接字编程的 INADDR_ANY

转载 作者:太空狗 更新时间:2023-10-29 16:15:57 30 4
gpt4 key购买 nike

我正在尝试对一些套接字进行编程,因此在服务器端,我使用 htonl(INADDR_ANY)。就我的理解而言,在我看来,这个函数生成了一个随机 IP(我说得对吗?)。事实上,我想将我的套接字与我的 localhost 绑定(bind)。但是如果我运行这个

printf("%d",htonl(INADDR_ANY));

我得到 0 作为返回值。有人可以解释一下吗?

最佳答案

    INADDR_ANY
  1. bind() NOT“生成随机 IP”。它binds the socket to all available interfaces .

  2. 对于服务器,您通常希望绑定(bind)到所有接口(interface) - 而不仅仅是“本地主机”。

  3. 如果您只想将套接字绑定(bind)到本地主机,语法为 my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1");,然后调用 bind (my_socket, (SOCKADDR *) &my_sockaddr, ...)

  4. 碰巧,INADDR_ANY 是一个恰好等于“零”的常量:

    http://www.castaglia.org/proftpd/doc/devel-guide/src/include/inet.h.html

    # define INADDR_ANY ((unsigned long int) 0x00000000)
    ...
    # define INADDR_NONE 0xffffffff
    ...
    # define INPORT_ANY 0
    ...
  5. 如果您还不熟悉它,我建议您查看 Beej 的套接字编程指南:

    http://beej.us/guide/bgnet/

由于人们仍在阅读本文,因此请注意:

man (7) ip:

When a process wants to receive new incoming packets or connections, it should bind a socket to a local interface address using bind(2).

In this case, only one IP socket may be bound to any given local (address, port) pair. When INADDR_ANY is specified in the bind call, the socket will be bound to all local interfaces.

When listen(2) is called on an unbound socket, the socket is automatically bound to a random free port with the local address set to INADDR_ANY.

When connect(2) is called on an unbound socket, the socket is automatically bound to a random free port or to a usable shared port with the local address set to INADDR_ANY...

There are several special addresses: INADDR_LOOPBACK (127.0.0.1) always refers to the local host via the loopback device; INADDR_ANY (0.0.0.0) means any address for binding...

还有:

bind() — Bind a name to a socket:

If the (sin_addr.s_addr) field is set to the constant INADDR_ANY, as defined in netinet/in.h, the caller is requesting that the socket be bound to all network interfaces on the host. Subsequently, UDP packets and TCP connections from all interfaces (which match the bound name) are routed to the application. This becomes important when a server offers a service to multiple networks. By leaving the address unspecified, the server can accept all UDP packets and TCP connection requests made for its port, regardless of the network interface on which the requests arrived.

关于c - 了解用于套接字编程的 INADDR_ANY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16508685/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com