为什么第一个客户端看到源 ip 为 0.0.0.0? [英] Why the first client sees to have source ip of 0.0.0.0?

查看:9
本文介绍了为什么第一个客户端看到源 ip 为 0.0.0.0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 linux 上有一个 client.c server.c.在两者上我都初始化了一个套接字:

I have a client.c server.c on linux. on both I init a socket:

sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)

在我添加的服务器中:

listen_addr.sin_family = AF_INET;
listen_addr.sin_port = htons(port);
listen_adrr.sin_addr.s_addr = htonl(INADDR_ANY);

server.c 调用(阻塞方式)到recvform:

the server.c calls (blocking way) to recvform:

if (recvfrom(sockfd, buf_get, BUFLEN, 0, (struct sockaddr*)&talker_addr, &slen) == -1)
            err("recvfrom()");

client.c 发送数据包:

if (sendto(sockfd, buf_sent, BUFLEN, 0, (struct sockaddr*)&serv_addr, slen) == -1)
        err("sendto()");

  1. 问题是在第一次调用 sendtoclient.c,服务器将客户端的 ip 视为 0.0.0.0,之后在第二个,第三个,...调用 client.c 获得一个 ip 和有一个合法的IP,例如127.0.0.3:3212.
  2. 另一个奇怪的事情是,如果我启动第二个新客户,它会得到ip 从第一次开始.
  1. The problem is that on the first calling to sendto from client.c, the servers sees the client's ip as 0.0.0.0, after that on the second, third,... calls the client.c get an ip and have a legal ip such as 127.0.0.3:3212.
  2. another weird thing is that if I start a second new client it gets ip from the first time.

推荐答案

确保在调用 recvfrom 之前将 slen 设置为 talker_addr 结构的大小.它将在 recvfrom 中设置值(这可以解释为什么它在后续调用中起作用),但如果初始值错误,第一次调用可能会得到垃圾.

Make sure you are setting slen to the size of the talker_addr struct before you call recvfrom. It will set the value (which may explain why it works in subsequent calls) in recvfrom but if there is a bad initial value, you may get garbage the first call.

slen = sizeof(struct sockaddr_in);

这篇关于为什么第一个客户端看到源 ip 为 0.0.0.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆