#include #include #include #include #include #include #include #include #include const char *host_name = "joe.cs.unca.edu" ; const char *serv_name = "nimhub" ; /* port 48002 */ int main(int argc, char *argv[]) { char in_buff[256] ; char num_read, num_written ; struct hostent *hp ; struct servent *sp ; struct sockaddr_in ipInfo ; struct in_addr ipNum ; int tcpPort ; int sd ; /* Get the host number */ hp = gethostbyname(host_name) ; if (hp == (struct hostent *) NULL) { fprintf(stderr, "No such machine: %s\n", host_name) ; exit(1) ; } bcopy((void *)hp->h_addr_list[0], (void *)&(ipNum.s_addr), hp->h_length) ; fprintf(stdout, "%s -> %s\n", hp->h_name, inet_ntoa(ipNum)) ; /* Get the port number */ sp = getservbyname(serv_name, "tcp") ; if (sp == (struct servent *) NULL) { fprintf(stderr, "No such tcp service: %s\n", serv_name) ; exit(1) ; } tcpPort = ntohs(sp->s_port) ; fprintf(stdout, "%s -> %d\n", sp->s_name, tcpPort) ; /* Create the socket address structure */ ipInfo.sin_family = AF_INET ; ipInfo.sin_port = htons(tcpPort) ; ipInfo.sin_addr.s_addr = ipNum.s_addr ; /* Create the socket */ sd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (sd < 0) { fprintf(stderr, "socket creation failed\n"); exit(1); } /* connect */ if (connect(sd, (struct sockaddr *)&ipInfo, sizeof(ipInfo))) { fputs("Connection failed\n", stderr) ; exit(1) ; } /* Write something */ /* Better be running "nc -l 48802" on joe */ num_written = write(sd, "Are you there joe?\n\r", 20) ; fprintf(stdout, "Wrote %d characters\n", num_written) ; /* Read something */ num_read = read(sd, in_buff, sizeof(in_buff)-1) ; fprintf(stdout, "Read %d characters\n", num_read) ; in_buff[num_read] = '\0' ; fprintf(stdout, "%s\n", in_buff) ; }