-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_client.c
74 lines (59 loc) · 1.94 KB
/
tcp_client.c
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
#include "net_include.h"
#define NAME_LENGTH 80
/* This was almost entirely stolen from the cs437 course example code at Johns Hopkins University. */
int main()
{
struct sockaddr_in host;
struct hostent h_ent, *p_h_ent;
char host_name[80];
char *c;
int s;
int ret;
uint32_t mess_len;
char mess_buf[MAX_MESS_LEN];
char *neto_mess_ptr = &mess_buf[sizeof(mess_len)];
s = socket(AF_INET, SOCK_STREAM, 0); /* Create a socket (TCP) */
if (s<0) {
perror("Net_client: socket error");
exit(1);
}
host.sin_family = AF_INET;
host.sin_port = htons(PORT);
printf("Enter the server name:\n");
if ( fgets(host_name,80,stdin) == NULL ) {
perror("net_client: Error reading server name.\n");
exit(1);
}
c = strchr(host_name,'\n'); /* remove new line */
if ( c ) *c = '\0';
c = strchr(host_name,'\r'); /* remove carriage return */
if ( c ) *c = '\0';
printf("Your server is %s\n",host_name);
p_h_ent = gethostbyname(host_name);
if ( p_h_ent == NULL ) {
printf("net_client: gethostbyname error.\n");
exit(1);
}
memcpy( &h_ent, p_h_ent, sizeof(h_ent) );
memcpy( &host.sin_addr, h_ent.h_addr_list[0], sizeof(host.sin_addr) );
ret = connect(s, (struct sockaddr *)&host, sizeof(host) ); /* Connect! */
if( ret < 0)
{
perror( "Net_client: could not connect to server");
exit(1);
}
for(;;)
{
printf("enter message: ");
scanf("%s",neto_mess_ptr);
mess_len = strlen(neto_mess_ptr);
memcpy( mess_buf, &mess_len, sizeof(mess_len) );
ret = send( s, mess_buf, mess_len + sizeof(mess_len), 0);
if(ret != (mess_len + sizeof(mess_len)))
{
perror( "Net_client: error in writing");
exit(1);
}
}
return 0;
}