Hello everyone,
I am trying to program an UDP talker using sockets.
My program compiles with no problems but when I try to execute it with any volume number, I am getting always the error : sendto : message too long
and I really don't know why !!
Here is the code of my UDP talker:
Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFSIZE 100000
int main(int argc, char **argv) {
int sfd, s, val, volume;
struct addrinfo hints;
struct addrinfo *result, *rp;
struct sockaddr *sa;
socklen_t salen;
char buf[BUFSIZE];
ssize_t nsend;
if (argc != 4) {
printf("Usage: %s service_adress server_port volume\n", argv[0]);
exit(EXIT_FAILURE);
}
volume = atoi(argv[3]);
if (volume == 0 || volume > BUFSIZE) {
fprintf(stderr, "give a volume less then %d bytes\n", BUFSIZE);
exit(EXIT_FAILURE);
}
/* buffer initializing */
memset(buf, 'a', volume);
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* IPv4 ou IPv6 */
hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
s = getaddrinfo(argv[1], argv[2], &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
/* open socket */
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd >= 0)
break;
}
if (rp == NULL) { /* no valid adress */
fprintf(stderr, "Unable to open a socket to %s\n", argv[1]);
perror("socket");
exit(EXIT_FAILURE);
}
/*
* Construction of the remote address structure
*/
sa=malloc(rp->ai_addrlen);
memcpy(sa, rp->ai_addr, rp->ai_addrlen);
salen=rp->ai_addrlen;
freeaddrinfo(result); /* Not needed anymore */
/* Allow broadcast (IPv4 only) */
val = 1;
if (setsockopt(sfd, SOL_SOCKET, SO_BROADCAST, &val, sizeof(val)) < 0) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
/* send data */
nsend = sendto(sfd, &buf, BUFSIZE, 0, (struct sockaddr *)&sa, salen);
if (nsend < 0)
perror("sendto");
exit(EXIT_SUCCESS);
}