我正在使用套接字在 C 中编写一个简单的消息传递应用程序。当我使用 functionrecvfrom
时,它返回-1
并设置errno = 14
which is Bad address
(我在最后打印)。
奇怪的是它仍然从套接字读取并得到正确的消息。也就是说,除了该错误之外,该应用程序运行良好且符合预期。
我的问题是:为什么你认为我会收到这个错误?我想不出任何理由。我inet_pton
用来设置peer->sin_addr
但我得到了同样的错误。
// socket file descriptor to send data through
int recv_sock_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
// fill in the peer's address, loopback in this case
struct sockaddr_in *peer = malloc(sizeof(struct sockaddr_in));
peer->sin_family = AF_INET;
peer->sin_port = htons(11110);
char *new = &(peer->sin_addr);
new[0] = 127;
new[1] = 0;
new[2] = 0;
new[3] = 1;
for (int i = 0; i < 8; i++) {
peer->sin_zero[i] = NULL;
}
bind(recv_sock_fd, peer, sizeof(struct sockaddr_in));
// check to see if the socket has any data...code removed
char buff[32] = {0};
errno = 0;
int bytes_received = recvfrom(recv_sock_fd, buff, sizeof(buff), NULL, (struct sockaddr *)peer, sizeof(struct sockaddr_in));
printf("Bytes recieved: %d: %d : %s\n", bytes_received, errno, strerror(errno));