metalsvm/newlib/examples/client.c

75 lines
1.5 KiB
C
Raw Permalink Normal View History

2011-08-10 08:22:23 +02:00
/* 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
2011-08-10 08:22:23 +02:00
#define MAX_BUF 100
#define N 10
2011-08-10 08:22:23 +02:00
int main(int argc, char* argv[])
{
int i, cmd;
2011-08-10 08:22:23 +02:00
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);
}
2011-09-18 18:02:25 +02:00
memset(&serv_name, 0x00, sizeof(serv_name));
2011-08-10 08:22:23 +02:00
/* 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));
2011-08-10 08:22:23 +02:00
close(sockd);
printf("Leave client...\n");
2011-08-10 08:22:23 +02:00
return 0;
}