/* A small example program to demonstrate converting among textual representation of hostname dotted decimal representation */ #include #include // calloc #include // memset, strncpy #include // hostent, gethostbyname #include // inet_ntop #include // inet_ntop #include // inet_ntop #include // close #define SIZE_MAX 31 int main (int argc, char* argv[]) { int i; char *hostname; char **pptr; char ipadd[INET_ADDRSTRLEN]; struct hostent *hptr; struct sockaddr_in servaddr; int sockfd; char buf[20]; if (argc != 2) { printf("Usage: \n"); return 1; } /**************** PART 1 ***********************/ hostname = calloc(SIZE_MAX, sizeof(char)); memset(hostname, '\0', SIZE_MAX); strncpy(hostname, argv[1], strlen(argv[1])); printf("\tHostname received from user = %s\n\n", hostname); if ( (hptr = gethostbyname(hostname)) == NULL) { // gethostbyname sets the h_errno value, not the errno printf("gethostbyname error : %s\n", hstrerror(h_errno)); return 1; } printf("\tOfficial hostname = %s\n", hptr->h_name); for (pptr = hptr->h_aliases; *pptr != NULL; pptr++) printf("\tAlias = %s\n", *pptr); if (hptr->h_addrtype == AF_INET) { for (pptr = hptr->h_addr_list; *pptr != NULL; pptr++) { // *pptr does not end with '\0' //printf("\tDotted decimal(weird!) = %s\n", *pptr); inet_ntop(AF_INET, *pptr, ipadd, INET_ADDRSTRLEN); printf("\tDotted decimal = %s\n", ipadd); } } /**************** PART 2 ***********************/ if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); return 1; } memset(&servaddr, '\0', sizeof(servaddr)); servaddr.sin_port = htons(3346); // connect to port inet_pton(AF_INET, ipadd, &servaddr.sin_addr); if ( (i = connect (sockfd, (struct sockaddr*) &servaddr, sizeof(servaddr))) < 0) { perror("Could not connect to port 80"); return 1; } printf("\tConnected.\n"); i = 0; i = send(sockfd, "hi", 2, 0); printf("\tSent %d.\n", i); recv(sockfd, buf, 10, 0); printf("buf = %s\n", buf); //close(sockfd); return 0; } // end of main