UNIX环境高级编程学习之第十六章网络IPC:套接字 – 简单TCP Socket 通信
[code lang=”cpp”]/* User:Lixiujie
* Date:20101122
* Desc:简单TCP通信,服务器端, 向客户端发送uptime信息。
* File:tcp_server.c
* System:Ubuntu 64bit
* gcc tcp_server.c tcp_server
* tcp_server 7878
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h> /* socket bind listen connect accept send recv */
#include <arpa/inet.h> /* htons ntohs htonl ntohl inet_addr inet_ntoa */
#include <netinet/in.h> /* sockaddr_in */

#define BUFLEN 128
#define QLEN 10

/* create tcp server */
int initserver(int type, const struct sockaddr *addr, socklen_t alen, int qlen){
int fd;
int err = 0;
/* 创建 */
if ((fd = socket(addr->sa_family, type, 0)) < 0){
return -1;
}
/* 绑定 */
if (bind(fd, addr, alen) < 0){
err = errno;
goto errout;
}
/* 监听数 */
if (SOCK_STREAM == type || SOCK_SEQPACKET == type){
if (listen(fd, qlen) < 0) {
err = errno;
goto errout;
}
}
return fd;
errout:
close(fd);
errno = err;
return -1;
}

int main(int argc, char *argv[]){
if (argc != 2){
printf("arg err!/n");
return -1;
}
int sefd, clfd, ret;
FILE *fp;
char szBuf[BUFLEN];
struct sockaddr_in se_addr,cl_addr;
socklen_t alen = sizeof(struct sockaddr);
/* 设置服务IP和端口 */
memset((void *)&se_addr, 0, alen);
se_addr.sin_family = AF_INET;
se_addr.sin_addr.s_addr = INADDR_ANY;// inet_addr("0.0.0.0");
se_addr.sin_port = htons(atoi(argv[1]));

if ((sefd = initserver(SOCK_STREAM, (struct sockaddr *)&se_addr, alen, QLEN)) > 0){
while (1){
alen = sizeof(struct sockaddr);
memset((void *)&cl_addr, 0 , alen);
clfd = accept(sefd, (struct sockaddr*)&cl_addr, &alen);
if (clfd < 0){
printf("accept err!/n");
close(sefd);
return -1;
}
printf("Client connect:ip=%s, port=%d /n", inet_ntoa(cl_addr.sin_addr), ntohs(cl_addr.sin_port));
if ((fp = popen("/usr/bin/uptime", "r")) == NULL){
memset(szBuf, 0, BUFLEN);
sprintf(szBuf, "error: %s/n", strerror(errno));
send(clfd, szBuf, strlen(szBuf), 0);
}else{
memset(szBuf, 0, BUFLEN);
while (fgets(szBuf, BUFLEN, fp) != NULL){
send(clfd, szBuf, strlen(szBuf), 0);
memset(szBuf, 0, BUFLEN);
}
pclose(fp);
}
close(clfd);
}
};
return 0;
}

[/code]

发表评论