/* ** udp_listener.c -- listens for udp packets */ #include #include #include #include #include #include #include #include #include #define MYPORT 4950 // the port i listen on #define MAXBUFLEN 256 // define the length of the receive buffer int main(void) { int sockfd; struct sockaddr_in my_addr; // my address information struct sockaddr_in their_addr; // connector's address information socklen_t addr_len; int numbytes; char buf[MAXBUFLEN]; // create a socket if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); exit(1); } my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(MYPORT); // short, network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero); // bind the socket to the port if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof my_addr) == -1) { perror("bind"); exit(1); } addr_len = sizeof their_addr; // recvfrom waits for a packet and returns the number of bytes read ... // typically this will be in a while loop to ensure that the whole message // is read if ((numbytes = recvfrom(sockfd, &buf, MAXBUFLEN-1 , 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { perror("recvfrom"); exit(1); } printf("got packet from %s\n",inet_ntoa(their_addr.sin_addr)); printf("packet is %d bytes long\n",numbytes); // terminate the received 'string' buf[numbytes] = '\0'; printf("packet contains \"%s\"\n", buf); close(sockfd); return 0; }