/* * selfid.c -- identify attributes of current host */ #include #include #include #include #include int main() { int sockfd; char hostname[MAXHOSTNAMELEN+1]; struct sockaddr_in saddr; int slen = sizeof(struct sockaddr_in); struct hostent *hp; char **p; if (gethostname(hostname, MAXHOSTNAMELEN) < 0) { perror("gethostname"); exit(1);} printf ("Hostname (from gethostname) = %s\n", hostname); if ((hp = gethostbyname(hostname)) == NULL) { perror("gethostbyname"); exit(1);} printf("Official Name (from gethostbyname) = %s\n", hp->h_name); p = hp->h_aliases; while (*p) { printf("ALIAS = %s\n", *p); p++;} printf("addrtype = %d\n", hp->h_addrtype); printf("length of address = %d\n", hp->h_length); p = hp->h_addr_list; while (*p) { printf("IP according to gethostbyname = %s\n", inet_ntoa(*p)); p++;} if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); exit(1);} bzero((char *)&saddr, sizeof(saddr)); saddr.sin_family = hp->h_addrtype; saddr.sin_port = htons(0); saddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) { perror("bind"); exit(1);} if (getsockname(sockfd, &saddr, &slen) < 0) { perror("getsockname"); exit(1);} printf("Socket Family = %u\n", ntohs(saddr.sin_family)); printf("Port = %u\n", ntohs(saddr.sin_port)); printf("IP = %s\n", inet_ntoa(saddr.sin_addr.s_addr)); exit(0); }