The Linux Networking Architecture [Electronic resources]

Klaus Wehrle

نسخه متنی -صفحه : 187/ 160
نمايش فراداده

G.2 CLIENT

/*********************************************************************
* Socket example: Chat application, client component comm_c.c
*
* Compilation: gcc -o comm_c comm_c.c
*********************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#define BUFSIZE 1024
char buf[BUFSIZE+1];
/* Main program:
* -   Process arguments.
* -   Open socket and establish connection to server.
* -   Read text line by line and send it over this connection.
* -   Close connection at end of entry (Ctrl-D).
*/
int main(int argc, char *argv[])
{
int s;
struct sockaddr_in addr;
char *p;
if (argc ! = 3) {
fprintf(stderr, "Usage: %s <address> <port>\n", argv[0]); exit(1);
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(argv[2]));
addr.sin_addr.s_addr = inet_addr(argv[1]);
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket"); exit(1);
}

if (connect(s, (struct sockaddr *) &addr, sizeof(addr))) {
perror("connect"); exit(1);
}
buf[BUFSIZE] = 0;
while (fgets(buf, BUFSIZE, stdin) != NULL) {
if (write(s, buf, strlen(buf)) == 0) {
perror("write"); break;
}
}
close(s);
exit(0);
}