/* udp4-s3.c: version 3 of sender - uses symbolic name for address */ #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { int s; /* s = socket */ struct sockaddr_in in_addr; /* Structure used for bind() */ struct sockaddr_in sock_addr; /* Output structure from getsockname */ struct sockaddr_in dest_addr; /* Destination socket */ char line[100]; char **p; int len; struct hostent *host_entry_ptr; /* Structure to receive output */ if (argc < 3) { printf("Usage: %s \n", argv[0]); printf(" Program sends messages to \n"); exit(1); } /* ------- Fill in destination socket - this will identify IP-host + (UDP) port ------- */ dest_addr.sin_family = AF_INET; /* Internet domain */ host_entry_ptr = gethostbyname(argv[1]); /* E.g.: cssun.mathcs.emory.edu */ if (host_entry_ptr == NULL) { printf("Host `%s' not found...\n", argv[1]); /* Just for safety.... */ exit(1); } /********************************************************************** * NOTE: DO NOT use htonl on the h_addr_list[0] returned by * gethostbyname() !!! **********************************************************************/ memcpy((char *) &(dest_addr.sin_addr.s_addr), host_entry_ptr->h_addr_list[0], host_entry_ptr->h_length); /**********************************************************************/ dest_addr.sin_port = htons(atoi(argv[2])); /* Destination (UDP) port # */ /* --- Create a socket --- */ s = socket(PF_INET, SOCK_DGRAM, 0); /* --- Set up socket end-point info for binding --- */ memset((char *)&in_addr, 0, sizeof(in_addr)); in_addr.sin_family = AF_INET; /* Protocol domain */ in_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Use wildcard IP address */ in_addr.sin_port = htons(0); /* Use any UDP port */ /* --- Here goes the binding... --- */ if (bind(s, (struct sockaddr *)&in_addr, sizeof(in_addr)) == -1) { printf("Error: bind FAILED\n"); } else { printf("OK: bind SUCCESS\n"); } /* ---- Check what port I got ---- */ len = sizeof(sock_addr); getsockname(s, (struct sockaddr *) &sock_addr, &len); printf("Socket s is bind to:\n"); printf(" addr = %u\n", ntohl(sock_addr.sin_addr.s_addr)); printf(" port = %d\n", ntohs(sock_addr.sin_port)); while(1) { printf("Enter a line: "); scanf("%[^\n]", &line); getchar(); /* ---- sendto() will automatically use UDP layer ---- */ sendto(s, line, strlen(line)+1, 0 /* flags */, (struct sockaddr *)&dest_addr, sizeof(dest_addr)); } }