summaryrefslogtreecommitdiff
path: root/sock.c
blob: 03a7c39a379011981201f8138e21e3b936e8a797 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/*
    Reader/writer to TCP/IP socket
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>

#include <stdio.h>
#include <errno.h>

char	*name;
int	sock;

char	*GetLine();
int	Connect();

main(argc,argv)
int argc;
char *argv[];

{
    struct sockaddr_in addr;
    int addrlen;
    char *p;
    char buff[1024];
    int len;

    name=argv[0];

    if (argc<3)
	{
	fprintf(stderr,"%s: usage %s host port [nowrite]\n",name,name);
	exit(1);
	}

    Connect(argv[1],atoi(argv[2]));

    /* Test to see how to get the connected local port number
    */
    addrlen=sizeof(addr);
    if (getsockname(sock,&addr,&addrlen)!=0)
	perror(name);

    printf("%s: bound through port %d\n",name,ntohs(addr.sin_port));

    while((argc==4)||(p=GetLine()))
	{
	if ((argc!=4)&&(write(sock,p,strlen(p))==-1))
	    {
	    perror(name);
	    close(sock);
	    exit(1);
	    }

	if ((len=read(sock,buff,1024))<=0)
	    {
	    perror(name);
	    close(sock);
	    exit(1);
	    }
	buff[len]=0;
	printf("%s\n",buff);
	}

    close(sock);
    printf("\n");

    return(0);
}


char *GetLine()

{
    static char buff[1024];
    int l;

    if (feof(stdin))
	return(NULL);

    printf("> ");

    if (!gets(buff))
	return(NULL);

    l=strlen(buff);

    if (buff[l-1]=='\n')
	buff[l-1]=0;

    if (strlen(buff))
	return(buff);
    else
	return(GetLine());
}


int Connect(n,p)
char *n;
int p;

{
    struct hostent *remote;
    struct sockaddr_in addr;

    if (!(remote=gethostbyname(n)))
	{
	fprintf(stderr,"%s: unknown host %s\n",name,n);
	exit(1);
	}

    bcopy(remote->h_addr,&addr.sin_addr,remote->h_length);

    if ((sock=socket(AF_INET,SOCK_STREAM,0))==-1)
	{
	perror(name);
	exit(1);
	}

    addr.sin_family=AF_INET;
    addr.sin_port=htons(p);

    if (connect(sock,&addr,sizeof(addr))==-1)
	{
	perror(name);
	exit(1);
	}
}