最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What is wrong with this simple IP example in C? - Stack Overflow

programmeradmin3浏览0评论

What is wrong with this simple piece of C code?

    int main(int argc, char **argv) {
            struct sockaddr_in servaddr;
            char buf[INET_ADDRSTRLEN];
    
            memset(&servaddr, 0, sizeof(servaddr));
            servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
            servaddr.sin_port = htons(22000);
            servaddr.sin_family = AF_INET;
            fprintf(stderr, "addrinfo: %s\n",
                       inet_ntop(AF_INET, &servaddr, buf, INET_ADDRSTRLEN));
       }

The code prints: addrinfo: 2.0.85.240

I would prefer it to print: addrinfo: 127.0.0.1

What is wrong with this simple piece of C code?

    int main(int argc, char **argv) {
            struct sockaddr_in servaddr;
            char buf[INET_ADDRSTRLEN];
    
            memset(&servaddr, 0, sizeof(servaddr));
            servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
            servaddr.sin_port = htons(22000);
            servaddr.sin_family = AF_INET;
            fprintf(stderr, "addrinfo: %s\n",
                       inet_ntop(AF_INET, &servaddr, buf, INET_ADDRSTRLEN));
       }

The code prints: addrinfo: 2.0.85.240

I would prefer it to print: addrinfo: 127.0.0.1

Share Improve this question edited Mar 31 at 6:47 Richard Melville asked Mar 31 at 5:34 Richard MelvilleRichard Melville 372 bronze badges New contributor Richard Melville is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 3
  • 2 Please add the few necessary lines to make this a complete program. I mean the #include lines and int main(). Now it is impossible to try the code (without adding more code, which then may be different from your code). – hyde Commented Mar 31 at 5:54
  • Please try to create a minimal reproducible example to show us. – Some programmer dude Commented Mar 31 at 6:08
  • 3 inet_ntop(AF_INET, &servaddr.sin_addr.s_addr, buf, INET_ADDRSTRLEN) – 4386427 Commented Mar 31 at 6:21
Add a comment  | 

1 Answer 1

Reset to default 5

The problem is that you are passing the address of the entire server structure to the inet_ntop function. But if you look at the documentation for the inet_ntop function, you will see that paddr should be "A pointer to the IP address in network byte [order] to convert to a string." So the call should be:

inet_ntop(AF_INET, &servaddr.sin_addr, buf, INET_ADDRSTRLEN));
发布评论

评论列表(0)

  1. 暂无评论