/* tcp-c1.c: illustrates a TCP client */ #include #include #include #include #include #include #include #include #include #include void int_handler(int dummy) { printf("Write error to socket... exiting....\n"); fflush(stdout); exit(1); } int 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; int x, y, z; 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); while ( 1 ) { printf("Enter first number (0 to exit): "); scanf("%d", &x); if ( x == 0 ) { close(s); exit(0); } printf("Enter second number: "); scanf("%d", &y); int x1, y1, z1; x1 = htonl(x); y1 = htonl(y); write(s, &x1, 4); write(s, &y1, 4); read(s, &z1, 4); z = htonl(z1); printf("%d + %d = %d\n", x, y, z); } printf("\nDone.\n"); }