I am trying to create my first UDP client server program in C language slightly modified from the man page of linux gai_strerror(3) - Linux man page. Although that I am using several error functions to check the correct process of the code when I reach the transmission part it fails. Based on what I see the connection is correct there is no error so in theory the message should be transmitted, but in practice it fails. I even open wireshark on local mode to see if there are any data transmitted, but nothing is transmitted. Since this is my first client Server program, and I am new into programing I can not think any other way to debug my code. What am I missing?
Addition:
On the terminal two things are printed:
connected: Success
and the error that is printing is Error sending data!
Any advice would be much appreciated.
#include <sys/types.h>
#include<errno.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <inttypes.h>
#include <sys/time.h> /* The header includes gettimeofday() */
#include <time.h> /* The header includes time types which we will use for day time */
#include <math.h> /* The header includes mathematical declarations */
int main(int argc, char *argv[]) {
struct timeval start; /* struct timeval for tv_sec and tv_usec */
struct addrinfo bind_info;
struct addrinfo *servInfo, *rp; /* addrinfo is filled with destination host information */
int socket_fd, retrieve_info; /* socket_fd represents the file descriptor of socket, rtt round time trip */
ssize_t send;
uint32_t tran = 0;
char *ip_serv = argv[1]; /* Set argv[1] as the server IP */
char *port_number = argv[2];
memset(&bind_info, 0, sizeof(struct addrinfo));
bind_info.ai_family = AF_INET;
bind_info.ai_socktype = SOCK_DGRAM;
bind_info.ai_protocol = IPPROTO_UDP;
bind_info.ai_flags = AI_PASSIVE;
if ((retrieve_info = getaddrinfo(ip_serv, port_number,&bind_info, &servInfo)) !=0 ) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(retrieve_info));
exit(EXIT_FAILURE);
}
for (rp = servInfo; rp != NULL; rp = rp->ai_next) {
if ((socket_fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) == -1) {
perror("socket");
continue;
}
if (connect(socket_fd, rp->ai_addr, rp->ai_addrlen) != -1) {
perror("connected");
break; /* We made it enough stop */
}
close(socket_fd); /* Release socket after binding */
}
if (rp == NULL) {
fprintf(stderr, "failed to connect\n");
exit(2);
}
freeaddrinfo(servInfo);
gettimeofday(&start, NULL); /* timezone should be NULL */
long int start_time = (start.tv_sec * 1000000 + start.tv_usec);
tran = htonl(start_time);
send = sendto(socket_fd,&tran,sizeof(tran),0,(struct sockaddr *) rp->ai_addr, rp->ai_addrlen);
if (send == 0) {
printf("Transmission to server was correct!\n");
}
else {
fprintf(stderr, "Error sending data!\n");
}
exit(0);
} /* end of int main (argv[]) */