简体   繁体   English

为什么inet_ntoa在此代码中返回0.0.0.0?

[英]Why inet_ntoa returns 0.0.0.0 in this code?

This is the code I'm trying: 这是我正在尝试的代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdint.h>
#include <string.h>

int main(){
    uint8_t dip[4]={127,0,0,1};
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = 5000;
    memcpy(&serv_addr, dip, 4);
    printf("IP: %s\n", inet_ntoa(serv_addr.sin_addr));

    return 0;
}

And this is the final result on my terminal 这是我终端上的最终结果

IP: 0.0.0.0

I don't understand why I obtained that result. 我不明白为什么我得到了那个结果。 Does anyone know what it's happening? 有人知道发生了什么吗?

The problem is in 问题出在

  memcpy(&serv_addr, dip, 4);

where you forgot to mention the target member (as nested struct in_addr ), you used the structure variable address instead. 在这里您忘记提及目标成员(作为嵌套struct in_addr ),而是使用结构变量地址。 Do it like 做喜欢

 memcpy(&(serv_addr.sin_addr), dip, 4);

and it should work. 它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM