This repository has been archived on 2025-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
zhangyang-libzt/tests/api_test/tcpclient4.c

63 lines
1.5 KiB
C
Raw Normal View History

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>
#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);
#define MSG_SZ 128
2016-06-14 16:01:19 -07:00
int main(int argc , char *argv[])
{
if(argc < 3) {
2016-06-27 15:50:03 -07:00
printf("usage: client <addr> <port>\n");
return 1;
}
int sock, port = atoi(argv[2]);
2016-06-14 16:01:19 -07:00
struct sockaddr_in server;
char message[MSG_SZ] , server_reply[MSG_SZ];
2016-06-14 16:01:19 -07:00
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1) {
2016-07-18 12:24:24 -07:00
printf("could not create socket");
}
server.sin_addr.s_addr = inet_addr(argv[1]);
2016-06-14 16:01:19 -07:00
server.sin_family = AF_INET;
server.sin_port = htons( port );
2016-06-14 16:01:19 -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!";
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;
}