/* * @(#)netcat.c--Copy to network port */ static char *what[]={ "@(#)netcat--Copy to network port", "@(#)Copyright 1996 ShadeTree Software,Inc.", "@(#)STS/KBS 2apr1996", 0, }; #include #include #include #include #include #include int debugl; extern int h_errno; main(ac,av) int ac; char *av[]; { int s; struct sockaddr_in sin; int c; struct hostent *hp; char buf[1024]; int bufr,bufw; char *hostname; int port; int eret; char *iam; iam = av[0]; hostname = (char *)0; port = -1; while(ac>1) { av++; ac--; if(ac%2 != 0) break; if(strcmp(*av,"-d")==0) { debugl = atoi(*++av); ac--; if(debugl) fprintf(stderr,"debugl = %d\n",debugl); } else if(strcmp(*av,"-h")==0) { hostname = *++av; ac--; if(debugl) fprintf(stderr,"hostname = %s\n",hostname); } else if(strcmp(*av,"-p")==0) { port = atoi(*++av); ac--; if(debugl) fprintf(stderr,"port = %d\n",port); } } if(ac!=1 || hostname==0 || port<0) { fprintf(stderr,"usage: %s [-d n] -h hostname -p portnumber\n",iam); return(1); } eret=0; setbuf(stderr,NULL); hp = gethostbyname(hostname); if(debugl) fprintf(stderr,"gethostbyname()=0x%x\n",hp); if(!hp) { herror(hostname); return(2); } for(;;) { s=socket(AF_INET, SOCK_STREAM, 0); if(debugl) fprintf(stderr,"socket()=%d\n",s); if(s<0) { perror("Can't open socket"); return(2); } memcpy( (char *)&sin.sin_addr.s_addr, hp->h_addr, hp->h_length); sin.sin_family = hp->h_addrtype; sin.sin_port = htons(port); if(debugl) fprintf(stderr,"sin.sin_addr.s_addr=0x%x\n",sin.sin_addr.s_addr); c=connect(s,(struct sockaddr *)&sin,sizeof(sin)); if(debugl) fprintf(stderr,"connect()=%d\n",c); if(c) { if(debugl) { sprintf(buf,"Connect to port %d on %s",port,hostname); perror(buf); } close(s); sleep(5); } else { break; } } if(fcntl(s, F_SETFL, fcntl(s,F_GETFL,0) & O_SYNC) == -1) { if(debugl) perror("fcntl(O_SYNC)"); } while((bufr=read(0,buf,sizeof(buf)))>0) { if(debugl) fprintf(stderr,"read()=%d\n",bufr); bufw=write(s,buf,bufr); if(debugl) fprintf(stderr,"write()=%d\n",bufw); if(bufr != bufw) { if(debugl) fprintf(stderr,"short write!\n"); eret=2; break; } } close(s); return(0); }