- 论坛徽章:
- 0
|
tcpserv09.c- #include "unp.h"
- int
- main(int argc, char **argv)
- {
- int listenfd, connfd;
- pid_t childpid;
- socklen_t clilen;
- struct sockaddr_in cliaddr, servaddr;
- void sig_chld(int);
- listenfd = Socket(AF_INET, SOCK_STREAM, 0);
- bzero(&servaddr, sizeof(servaddr));
- servaddr.sin_family = AF_INET;
- servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
- servaddr.sin_port = htons(SERV_PORT);
- Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
- Listen(listenfd, LISTENQ);
- Signal(SIGCHLD, sig_chld);
- for ( ; ; ) {
- clilen = sizeof(cliaddr);
- if ( (connfd = accept(listenfd, (SA *) &cliaddr, &clilen)) < 0) {
- if (errno == EINTR)
- continue; /* back to for() */
- else
- err_sys("accept error");
- }
- if ( (childpid = Fork()) == 0) { /* child process */
- Close(listenfd); /* close listening socket */
- str_echo(connfd); /* process the request */
- exit(0);
- }
- Close(connfd); /* parent closes connected socket */
- }
- }
复制代码 tcpcli09.c- #include "unp.h"
- int
- main(int argc, char **argv)
- {
- int sockfd;
- struct sockaddr_in servaddr;
- if (argc != 2)
- err_quit("usage: tcpcli <IPaddress>");
- sockfd = Socket(AF_INET, SOCK_STREAM, 0);
- bzero(&servaddr, sizeof(servaddr));
- servaddr.sin_family = AF_INET;
- servaddr.sin_port = htons(SERV_PORT);
- Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
- Connect(sockfd, (SA *) &servaddr, sizeof(servaddr));
- str_cli(stdin, sockfd); /* do it all */
- exit(0);
- }
复制代码 |
|