/* * From the BSD 4.4 IPC tutorial. * Figure 6a - Reading Internet domain datagrams. */ #include #include #include #include #include main() { int sock, length; struct sockaddr_in name; char buf[1024], hostname[512]; sock = socket(AF_INET, SOCK_DGRAM, 0); if(sock < 0){ perror("opening datagram socket"); exit(1); } name.sin_family = AF_INET; name.sin_addr.s_addr = INADDR_ANY; name.sin_port = 0; if(bind(sock, &name, sizeof(name)) < 0){ perror("bind"); exit(1); } length = sizeof(name); if(getsockname(sock, &name, &length) < 0){ perror("getting socket name"); exit(1); } gethostname(hostname, sizeof(hostname)); printf("host %s port %d\n", hostname, ntohs(name.sin_port)); if(read(sock, buf, 1024) < 0) perror("receiving datagram packet"); printf("-->%s\n", buf); close(sock); exit(0); }