为什么第一个客户端看到源 ip 为 0.0.0.0?第一个、客户端、ip

由网友(年轻、没有失败)分享简介:我在 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)...

我在 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()");

问题是在第一次调用 sendtoclient.c,服务器将客户端的 ip 视为 0.0.0.0,之后在第二个,第三个,...调用 client.c 获得一个 ip 和有一个合法的IP,例如127.0.0.3:3212.另一个奇怪的事情是,如果我启动第二个新客户,它会得到ip 从第一次开始. 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. 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);
阅读全文

相关推荐

最新文章