Simple messaging application…getting errno 14: bad address

十年热恋 提交于 2019-12-22 07:50:10

问题


I am writing a simple messaging application in C using sockets. When I use function recvfrom, it returns -1 and sets errno = 14 which is Bad address (which I am printing at the end).

The strange thing is that it still reads from the socket and gets the correct message. That is, the application is working perfectly and as expected except for that error.

My question is this: Why do you think I am getting this error? I cannot think of any reason. I was using inet_pton to set peer->sin_addr but I was getting the same error.

// 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));

回答1:


Look at the signature of recvfrom(2):

ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,
                 struct sockaddr *src_addr, socklen_t *addrlen);

Last argument is an address, while you are giving it a plain integer.

Then you're building of the IP address is wrong. Do use inet_pton(3), that's what it's for. Also check the return value of the bind(2), it's surely failing now.



来源:https://stackoverflow.com/questions/8320090/simple-messaging-application-getting-errno-14-bad-address

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!