【问题标题】:socket - read IP address from terminalsocket - 从终端读取 IP 地址
【发布时间】:2014-11-05 09:19:55
【问题描述】:

我正在以这种方式从终端读取地址以将客户端连接到服务器,但有人告诉我这是不正确的,因为我应该通过 inet_pton 函数对其进行转换。这是真的?你能解释一下为什么吗? 我正在使用 127.0.0.1 进行测试,这段代码似乎一切正常。地址是程序名后的第一个参数...

int main(int argc, char *argv[]){
    struct sockaddr_in Eaddr;
    Eaddr.sin_addr.s_addr=inet_addr(argv[1]);
    //other code to connect...
}

【问题讨论】:

    标签: c sockets ip inet


    【解决方案1】:

    inet_addr 的问题在于它指示错误返回INADDR_NONE,这与 IP 地址 255.255.255.255 一致。 inet_pton 函数有更好的错误报告:成功时返回 1,错误时返回 0 或 -1。

    【讨论】:

      【解决方案2】:

      来自inet_addr() man page

         The inet_addr() function converts the Internet host address cp from
         IPv4 numbers-and-dots notation into binary data in network byte
         order.  If the input is invalid, INADDR_NONE (usually -1) is
         returned.  Use of this function is problematic because -1 is a valid
         address (255.255.255.255).  Avoid its use in favor of inet_aton(),
         inet_pton(3), or getaddrinfo(3), which provide a cleaner way to
         indicate error return.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-26
        • 2017-10-21
        • 1970-01-01
        • 1970-01-01
        • 2011-10-14
        • 2012-01-02
        • 2016-06-30
        • 1970-01-01
        相关资源
        最近更新 更多