/* tcp-c1.c: illustrates a TCP client */ #include #include #include #include #include #include #include #include #include main(int argc, char *argv[]) { int s; /* s = socket */ struct sockaddr_in server; /* Server's Internet address */ struct hostent *host_entry_ptr; /* Translate hostname to IP addr */ char c; struct sockaddr_in myname; int myname_len; if (argc < 3) { printf("Usage: %s host port\n", argv[0]); exit(1); } /* --- Create a socket --- */ s = socket(AF_INET, SOCK_STREAM, 0); /* --- Set up Server's Internet address - This is the same as in UDP --- */ server.sin_family = AF_INET; /* Put in the family */ host_entry_ptr = gethostbyname(argv[1]); /* Get host info from name */ if (host_entry_ptr == NULL) { printf("Host `%s' not found...\n", argv[1]); exit(1); } memcpy((char *) &(server.sin_addr.s_addr), host_entry_ptr->h_addr, host_entry_ptr->h_length); /* Server's IP addr */ server.sin_port = htons(atoi(argv[2])); /* Server's port number */ /* ---------------------------------------------- Here goes...... ---------------------------------------------- */ if (connect(s, (struct sockaddr *) &server, sizeof(server) ) < 0) { printf("Error: can't connect to %s port %s...\n", argv[1], argv[2]); exit(1); } /* --------------------------------------- Print info of the data socket --------------------------------------- */ myname_len = sizeof(myname); getsockname(s, (struct sockaddr *) &myname, &myname_len); printf("The TCP connection is:\n"); printf("==============================\n"); printf("My network address is:\n"); printf(" sin_addr.s_addr = %u\n", myname.sin_addr.s_addr); printf(" sin_port = %u\n\n", myname.sin_port); /* ------------------------------------------- Print info of peer socket ------------------------------------------- */ myname_len = sizeof(myname); getpeername(s, (struct sockaddr *) &myname, &myname_len); printf("The peer socket (server) network address is:\n"); printf(" sin_addr.s_addr = %u\n", myname.sin_addr.s_addr); printf(" sin_port = %u\n\n", myname.sin_port); printf("Now type away...\n"); while ((c = getchar()) != EOF ) { write(s, &c, 1); } close(s); printf("\nDone.\n"); }