Hi, I have 2 programs; UDP sender and receiver. These programs are absolutely basic, trying to get the concept and understand how it works. I specify the target IP and port via arguments in the sender, in the receiver I only specify the port number. The sender sends a message and waits for an ACK then exits. The receiver waits on recvfrom() and I do not understand why. I thought INADDR_ANY binded all interfaces to the program so any packet is received by it. Maybe I'm overlooking a syntax error, but I do not see why it isn't working. Here is the receiver code
Thanks for helping me debug!Code:#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <strings.h> #include <netdb.h> #include <stdio.h> void error(char *msg) { perror(msg); exit(0); } int main(int argc, char *argv[]) { int sock, length, fromlen, n; struct sockaddr_in server; struct sockaddr_in from; char buf[1024]; if (argc < 2) { fprintf(stderr, "ERROR, no port provided\n"); exit(0); } sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) error("Opening socket"); length = sizeof(server); bzero(&server,length); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(atoi(argv[1])); if ( bind(sock,(struct sockaddr *) &server,length) < 0 ) error("binding"); fromlen = sizeof(struct sockaddr_in); printf("Waiting to recv.\n"); fflush(stdout); while (1) { n = recvfrom(sock, buf, 1024, 0, (struct sockaddr *) &from, &fromlen); if (n < 0) error("recvfrom"); printf("Received a datagram.\n"); fflush(stdout); printf("%s\n", buf); fflush(stdout); n = sendto(sock, "Got your message\n", 17, 0, (struct sockaddr *) &from, fromlen); if (n < 0) error("sendto"); } // while return(1); } // main
Chris



LinkBack URL
About LinkBacks



