深入理解计算机系统(网络编程)

#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>

typedef struct sockaddr SA;
int open_clientfd(char * hostname, int port)
{
	int clientfd;
	struct hostent * hp;
	struct sockaddr_in serveraddr;

	if ((clientfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		return -1;
	}
	if ((hp = gethostbyname(hostname)) == NULL) {
		return -2;
	}
	bzero((char *)&serveraddr, sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	bcopy((char *)hp->h_addr, (char *)&serveraddr.sin_addr.s_addr, hp->h_length);
	serveraddr.sin_port = htons(port);
	if (connect(clientfd, (SA *)&serveraddr, sizeof(serveraddr)) < 0)
		return -1;
	return clientfd;
}

int main(int argc, char **argv)
{
	int ret;
	ret = socket(AF_INET, SOCK_STREAM, 0);

	char **pp;
	struct in_addr addr;
	struct hostent *hostp;

	if (argc != 2) {
		fprintf(stderr, "usage error\n");
		exit(0);
	}
	if (inet_aton(argv[1], &addr) != 0) {
		hostp = gethostbyaddr((const char *)&addr, sizeof(addr), AF_INET);
	} else {
		hostp = gethostbyname(argv[1]);
	}

	printf("official hostname: %s\n", hostp->h_name);

	for (pp = hostp->h_aliases; *pp != NULL; ++pp) {
		printf("alias: %s\n", *pp);
	}

	for (pp = hostp->h_addr_list; *pp != NULL; ++pp) {
		addr.s_addr = *((unsigned int * )*pp);
		printf("address: %s\n", inet_ntoa(addr));
	}

	return 0;
}


你可能感兴趣的:(深入理解计算机系统(网络编程))