We have been working on a project with UDP communication. The requirement is to send data periodically over ethernet to UDP client. With much difficulty we modified the UDP example code. But does not seem to be working. Tried debugging the code, the "sendto" function was returning -1 value.The code snippet below. Could you guide me how to do this. Will the old NDK version support UDP communication? Thank you in advance.
Void udp_func(int argc, char **argv)
{
int sockfd, portno, n;
int serverlen;
struct sockaddr_in serveraddr;
struct hostent *server;
char *hostname;
char buf[BUFSIZE];
/* check command line arguments */
if (argc != 3) {
fprintf(stderr,"usage: %s <hostname> <port>\n", argv[0]);
exit(0);
}
hostname = argv[1];
portno = atoi(argv[2]);
/* socket: create the socket */
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
/* gethostbyname: get the server's DNS entry */
// server = gethostbyname(hostname);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host as %s\n", hostname);
exit(0);
}
/* build the server's Internet address */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_len = sizeof(serveraddr);
serveraddr.sin_addr.s_addr = inet_addr("192.168.0.184");
serveraddr.sin_port = htons(2000);
strcpy(buf,"test_data");
/* send the message to the server */
serverlen = sizeof(serveraddr);
n = sendto(sockfd, buf, strlen(buf), 0, &serveraddr, serverlen);
if (n < 0)
error("ERROR in sendto");
/* print the server's reply */
n = recvfrom(sockfd, buf, strlen(buf), 0, &serveraddr, &serverlen);
if (n < 0)
error("ERROR in recvfrom");
printf("Echo from server: %s", buf);
return 0;
}