-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_client.c
101 lines (83 loc) · 2.27 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
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
/*
* tcpclient.c - A simple TCP client
* usage: tcpclient <host> <port>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define BUFSIZE 1024
int main(int argc, char **argv)
{
int sockfd, portno, n;
struct sockaddr_in serveraddr;
struct hostent *server;
char *hostname;
char buf[BUFSIZE];
/* check command line arguments */
if (argc != 4) {
fprintf(stderr,"usage: %s <hostname> <port> <value>\n", argv[0]);
exit(0);
}
hostname = argv[1];
portno = atoi(argv[2]);
/* socket: create the socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
printf("ERROR opening socket");
/* gethostbyname: get the server's DNS entry */
server = gethostbyname(hostname);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host as %s\n", hostname);
exit(0);
}
/* build the server's Internet address */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(portno);
/* connect: create a connection with the server */
if (connect(sockfd, (const struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) {
printf("ERROR connecting\n");
exit(1);
}
/* get message line from the user */
printf("Sending 0 1 0\n");
buf[0] = 0;
buf[1] = 1;
buf[2] = atoi(argv[3]);
n = write(sockfd, buf, 3);
if (n < 0) {
printf("ERROR writing to socket\n");
exit(1);
}
int temp;
buf[0] = 1;
buf[1] = 0;
n = write(sockfd, buf, 2);
if (n < 0) {
printf("ERROR writing to socket\n");
exit(1);
}
n = read(sockfd, temp, sizeof(temp));
if (n < 0) {
printf("ERROR writing to socket\n");
exit(1);
}
printf("Temperature %d\n", temp);
/* print the server's reply */
#if 0
bzero(buf, BUFSIZE);
n = read(sockfd, buf, BUFSIZE);
if (n < 0)
printf("ERROR reading from socket");
printf("Echo from server: %s", buf);
#endif
close(sockfd);
return 0;
}