Simple messaging application...getting errno 14: bad address

mmtauqir picture mmtauqir · Nov 30, 2011 · Viewed 11.5k times · Source

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

Answer

Nikolai Fetissov picture Nikolai Fetissov · Nov 30, 2011

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.