#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <unistd.h>
#include <termios.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#define BUFFER_SIZE 32
{
int count = 3;
char *pch;
while(count)
{
pch = strstr(pch, ".");
if(pch == NULL) return -1;
pch++;
count--;
}
return 0;
}
int main(
int argc,
char* argv[])
{
int i = 0;
int rc = 0;
char ch = 0;
char chIgnore = 0;
char ip[17];
char ipFlag = 0;
unsigned short port = 2323;
int sockfd = 0;
int nBytes = 0;
struct sockaddr_in sockAddress;
memset(ip, 0, sizeof(ip));
while((rc = getopt(argc, argv, "hi:p:")) != -1)
{
switch(rc)
{
case 'i':
{
printf("Invalid IP\r\n");
exit(1);
}
strcpy(ip, optarg);
ipFlag = 1;
break;
case 'p':
port = atoi(optarg);
break;
case '?':
case 'h':
default:
printf("Echo Server, client program.\n\n");
printf("Usage: ./client_tcp_echo [OPTIONS]\n\n");
printf("Options:\n");
printf("\t%-8s IP\n", "-i");
printf("\t%-8s Port [%d-%d]. Default port = %d\n", "-p", 0, 65535, port);
printf("\n");
return;
}
}
if(ipFlag == 0)
{
printf("No IP\r\n");
exit(1);
}
memset(sendBuf, 0, sizeof(sendBuf));
for(i = 0; i < 26; i++) sendBuf[i] = 'a' + i;
sendBuf[26] = '\0';
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
sockAddress.sin_family = AF_INET;
sockAddress.sin_port = htons(port);
sockAddress.sin_addr.s_addr = inet_addr(ip);
bzero(&(sockAddress.sin_zero), 8);
if(connect(sockfd, (struct sockaddr*)&sockAddress, sizeof(struct sockaddr)) == -1)
{
close(sockfd);
perror("connect");
exit(1);
}
while(1)
{
nBytes = write(sockfd, sendBuf, strlen(sendBuf));
if(nBytes == -1 || nBytes == 0)
{
close(sockfd);
printf("Server is closing...\r\n");
break;
}
printf("Send %d bytes\r\n", nBytes);
memset(receiveBuf, 0, sizeof(receiveBuf));
nBytes = read(sockfd, receiveBuf, sizeof(receiveBuf));
if(nBytes == -1 || nBytes == 0)
{
close(sockfd);
printf("Server is closing...\r\n");
break;
}
printf("Receive %d bytes, data = %s\r\n", nBytes, receiveBuf);
printf("Please keyin 'c' to send again or 'q' to exit.\r\n");
ch = getchar();
while(1)
{
chIgnore = getchar();
if(chIgnore == 0xa) break;
}
if(ch == 'c') continue;
else if(ch == 'q')
{
close(sockfd);
break;
}
else
{
close(sockfd);
printf("Unknow characters...\r\n");
break;
}
}
return 0;
}