Unix 'C' Program for TCP/IP Communications with Progress

Chris Kelleher

Administrator
Staff member
<BLOCKQUOTE><font size="1" face="Arial, Verdana">code:</font><HR><pre>INPUT-OUTPUT THROUGH VALUE("cl hostname portnumber") NO-ECHO.
REPEAT:
IMPORT UNFORMATTED x.
PUT UNFORMATTED y + CHR(10).
END.
INPUT-OUTPUT CLOSE.
[/code]
 

Chris Kelleher

Administrator
Staff member
<BLOCKQUOTE><font size="1" face="Arial, Verdana">code:</font><HR><pre>#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>

#define BUFSIZE 16384
extern int errno;

main(int argc, char **argv)
{ FILE *fp;
FILE *w_stdin;
FILE *w_stdout;
char x;
int id;
char hostname[64];
char buffer_in[BUFSIZE];
char buffer_out[BUFSIZE];
char *Machine = argv[1];
char *PortNo = argv[2];
struct hostent *hp;
struct sockaddr_in sin;
register int s,j,k,l;
w_stdin=stdin;
w_stdout=stdout;
if (argc!=3)
{ fprintf(stderr, "usage: %s hostname portnumber\n",argv[0]);
exit(-1);
}
gethostname(hostname, sizeof(hostname));
if ((hp=gethostbyname(Machine)) == NULL ) {
fprintf(stderr, "%s: unknown hostname", Machine);
exit(-2);
}
if ((s=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("server: socket not available");
exit(-3);
}
bzero((char *)&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(atoi(PortNo));
bcopy(hp->h_addr, (char *)&sin.sin_addr, hp->h_length);
if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
perror("client: connect not possible");
exit(-4);
}
fp = fdopen(s, "rb+");
if ((id=fork())==0)
{ while (fgets(buffer_in,sizeof(buffer_in),fp)!=NULL)
{ fputs(buffer_in,w_stdout);
fflush(w_stdout);
}
} else
{ while (fgets(buffer_out,sizeof(buffer_out),w_stdin)!=NULL)
{ fputs(buffer_out,fp);
fflush(fp);
}
}
if (id!=0)
{ sleep(2);
kill(id,SIGTERM);
}
close(s);
exit(0);
}

[/code]
 
Top