74 lines
1.5 KiB
C
74 lines
1.5 KiB
C
/* derived form http://www.cs.put.poznan.pl/csobaniec/examples/sockets/client-tcp-simple.c */
|
|
|
|
#include <sys/types.h>
|
|
#include <sys/socket.h>
|
|
#include <netinet/in.h>
|
|
#include <arpa/inet.h>
|
|
#include <string.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
#include <errno.h>
|
|
|
|
#define QUIT 0
|
|
#define S2C 1
|
|
#define MAX_BUF 100
|
|
#define N 10
|
|
|
|
int main(int argc, char* argv[])
|
|
{
|
|
int i, cmd;
|
|
int sockd;
|
|
int count;
|
|
struct sockaddr_in serv_name;
|
|
char buf[MAX_BUF];
|
|
int status;
|
|
|
|
if (argc < 3)
|
|
{
|
|
fprintf(stderr, "Usage: %s ip_address port_number\n", argv[0]);
|
|
exit(1);
|
|
}
|
|
/* create a socket */
|
|
sockd = socket(AF_INET, SOCK_STREAM, 0);
|
|
if (sockd == -1)
|
|
{
|
|
perror("Socket creation");
|
|
exit(1);
|
|
}
|
|
|
|
memset(&serv_name, 0x00, sizeof(serv_name));
|
|
/* server address */
|
|
serv_name.sin_family = AF_INET;
|
|
inet_aton(argv[1], &serv_name.sin_addr);
|
|
serv_name.sin_port = htons(atoi(argv[2]));
|
|
|
|
/* connect to the server */
|
|
status = connect(sockd, (struct sockaddr*)&serv_name, sizeof(serv_name));
|
|
if (status == -1)
|
|
{
|
|
perror("Connection error");
|
|
exit(1);
|
|
}
|
|
|
|
for(i=0, cmd=S2C; i<N; i++) {
|
|
// request new message
|
|
write(sockd, &cmd, sizeof(int));
|
|
|
|
// dump current value of i
|
|
snprintf(buf, MAX_BUF, "%d. ", i);
|
|
write(1, buf, strlen(buf));
|
|
|
|
// read new message and dump the incoming message on the screen
|
|
count = read(sockd, buf, MAX_BUF);
|
|
write(1, buf, count);
|
|
}
|
|
cmd = QUIT;
|
|
write(sockd, &cmd, sizeof(int));
|
|
|
|
close(sockd);
|
|
|
|
printf("Leave client...\n");
|
|
|
|
return 0;
|
|
}
|