2016-06-27 15:50:03 -07:00
|
|
|
// TCP Client test program
|
|
|
|
|
|
|
|
|
|
#include <stdio.h>
|
|
|
|
|
#include <string.h>
|
|
|
|
|
#include <sys/socket.h>
|
|
|
|
|
#include <arpa/inet.h>
|
2016-11-15 16:18:26 -08:00
|
|
|
#include <unistd.h>
|
2016-06-14 16:01:19 -07:00
|
|
|
|
2016-07-18 12:24:24 -07:00
|
|
|
int atoi(const char *str);
|
|
|
|
|
int close(int filedes);
|
|
|
|
|
|
2016-11-15 16:18:26 -08:00
|
|
|
#define MSG_SZ 128
|
|
|
|
|
|
2016-06-14 16:01:19 -07:00
|
|
|
int main(int argc , char *argv[])
|
|
|
|
|
{
|
2016-06-20 12:37:14 -07:00
|
|
|
if(argc < 3) {
|
2016-06-27 15:50:03 -07:00
|
|
|
printf("usage: client <addr> <port>\n");
|
|
|
|
|
return 1;
|
2016-06-20 12:37:14 -07:00
|
|
|
}
|
|
|
|
|
|
2016-06-20 16:21:28 -07:00
|
|
|
int sock, port = atoi(argv[2]);
|
2016-06-14 16:01:19 -07:00
|
|
|
struct sockaddr_in server;
|
2016-11-15 16:18:26 -08:00
|
|
|
char message[MSG_SZ] , server_reply[MSG_SZ];
|
2016-06-14 16:01:19 -07:00
|
|
|
|
|
|
|
|
sock = socket(AF_INET , SOCK_STREAM , 0);
|
2016-06-20 12:37:14 -07:00
|
|
|
if (sock == -1) {
|
2016-07-18 12:24:24 -07:00
|
|
|
printf("could not create socket");
|
2016-06-20 12:37:14 -07:00
|
|
|
}
|
|
|
|
|
server.sin_addr.s_addr = inet_addr(argv[1]);
|
2016-06-14 16:01:19 -07:00
|
|
|
server.sin_family = AF_INET;
|
2016-06-20 12:37:14 -07:00
|
|
|
server.sin_port = htons( port );
|
2016-06-14 16:01:19 -07:00
|
|
|
|
2016-06-20 12:37:14 -07:00
|
|
|
printf("connecting...\n");
|
2016-06-27 15:50:03 -07:00
|
|
|
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0) {
|
2016-06-14 16:01:19 -07:00
|
|
|
perror("connect failed. Error");
|
|
|
|
|
return 1;
|
|
|
|
|
}
|
2016-07-18 12:24:24 -07:00
|
|
|
printf("connected\n");
|
2016-07-03 12:01:30 -05:00
|
|
|
|
2016-07-18 14:28:46 -07:00
|
|
|
char *msg = "welcome to the machine!";
|
2016-11-15 16:18:26 -08:00
|
|
|
|
|
|
|
|
while(1)
|
|
|
|
|
{
|
|
|
|
|
// TX
|
|
|
|
|
if(send(sock, msg, strlen(msg), 0) < 0) {
|
|
|
|
|
printf("send failed");
|
|
|
|
|
return 1;
|
|
|
|
|
}
|
|
|
|
|
else {
|
|
|
|
|
printf("TX: %s\n", msg);
|
|
|
|
|
printf("len = %ld\n", strlen(msg));
|
|
|
|
|
|
|
|
|
|
int bytes_read = read(sock, server_reply, MSG_SZ);
|
|
|
|
|
if(bytes_read < 0)
|
|
|
|
|
printf("\tRX: Nothing\n");
|
|
|
|
|
else
|
|
|
|
|
printf("\tRX = (%d bytes): %s\n", bytes_read, server_reply);
|
|
|
|
|
}
|
2016-06-14 16:01:19 -07:00
|
|
|
}
|
|
|
|
|
close(sock);
|
|
|
|
|
return 0;
|
|
|
|
|
}
|