Einführung in die Netzwerkprogrammierung:tcpclient.c

aus PUG, der Penguin User Group
Wechseln zu: Navigation, Suche
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <netdb.h>
extern int h_errno;
#include <arpa/inet.h>
#include <stdio.h>

#define MAX_STRING_SIZE 1024

int main (int argc, char ** argv) {
	int fd;
	struct sockaddr_in remote;
	char server_addr[16], server_port[6], server_ip[16];
	struct hostent * server_entry;
	int slen;
	char string[MAX_STRING_SIZE], returnstring[MAX_STRING_SIZE];

	if (argc<3) {
		printf("too few arguments\n");
		printf("Usage: %s <server> <port>\n\n", argv[0]);
		exit(1);
	}
	strcpy(server_addr, argv[1]);

	// get ip address to server name
 	if ((server_entry=gethostbyname(server_addr)) == NULL) {
		printf("gethostbyname failed\n");
		exit(h_errno);
	}
	strcpy(server_port, argv[2]);
	strcpy(server_ip, inet_ntoa(*(struct in_addr*)server_entry->h_addr_list[0]));
	printf("connecting to %s (%s) on port %s\n", server_addr, server_ip, server_port);

	// open tcp socket
	if ((fd=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("socket error");
		exit(errno);
	}

	// fill structure "remote" with remote address
	remote.sin_family=AF_INET;
	remote.sin_port=htons(atoi(server_port));
	remote.sin_addr.s_addr=inet_addr(server_ip);
	memset(&remote.sin_zero, 0, sizeof(remote.sin_zero));

	// connect to server "remote"
	if (connect(fd, (struct sockaddr*)&remote, sizeof(remote)) < 0) {
		perror("connect error");
		exit(errno);
	}
	printf("established!\n");

	// read from stdin
	while((fgets(string, MAX_STRING_SIZE, stdin))>0) {
		slen=strlen(string)+1;
		if (slen==2) {
			printf("Closing connection\n");
			close(fd);
			exit(0);
		}
		printf("Sending %d chars\n", slen);
		// send chars to server
		write(fd, string, slen);
		// receive answer from server
		slen=read(fd, returnstring, sizeof(returnstring));
		printf("Server answered: %s\n", returnstring);
	}
}