/* dgrecv.c */ /* Demonstates the use of recvfrom for datagram transfer */ #define begin { #define end } #include #include #include #include #include char buf[100]; struct hostent *hp; struct hostent *gethostbyname(); struct sockaddr_in name; struct sockaddr_in sname; int namelen; main(argc, argv) int argc; char *argv[]; begin int i; unsigned char c; int sock; int netaddr; int status; /* Create datagram socket */ sock = socket(PF_INET, SOCK_DGRAM, 0); if (sock < 0) begin printf("Socket create failed \n"); exit(1); end /* Get host network address from command line parm */ hp = gethostbyname(argv[1]); if (hp == 0) begin printf("Host %s not found\n", argv[1]); exit(1); end bcopy((char *)hp->h_addr, (char *)&name.sin_addr, hp->h_length); /* Fill in protocol family and port # from command line then */ /* bind the socket to the specified address. */ name.sin_family = AF_INET; name.sin_port = htons(atoi(argv[2])); status = bind(sock, (struct sockaddr *)&name, sizeof(name)); printf("Bind status = %d \n", status); if (status < 0) exit(1); /* Wait for someone to send me a datagram */ namelen = sizeof(struct sockaddr_in); status = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&sname, &namelen); printf("status = %d \n", status); printf("Msg = %s \n", buf); printf("Sender net address = "); for (i = 0; i < hp->h_length; i++) begin c = *((char *)&sname.sin_addr + i); printf(" %2x", c); end printf("\n"); printf("Sender port address = %x \n", sname.sin_port); end