// louis 2004-8-21
#include<stdio.h>
#include<sys/socket.h>
#include<syslog.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define PORT 1234
int main()
{
int sockfd, clientfd, childpid;
struct sockaddr_in addr, cliaddr;
int len = sizeof(struct sockaddr_in);
char buf[256];
memset(buf, 0, 256);
// bzero(buf, 256);
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
//perror("");
}
// fill in struct sockaddr_in
bzero(&addr, len);
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd, (struct sockaddr *)&addr, len) < 0){
syslog(LOG_LOCAL4 | LOG_INFO, "[test] bind error");
exit(1);
}
if(listen(sockfd, 5)<0){
syslog(LOG_LOCAL4 | LOG_INFO, "[test] listen error");
exit(1);
}
while(1){
clientfd = accept(sockfd, (struct sockaddr *)&cliaddr, &len);
if((childpid = fork()) == 0){ // child process
close(sockfd);
// handle the clientfd;
while(1){
if(recv(clientfd, buf, 256, 0) != -1){
char *p = strstr(buf, "/r/n");
*p = '/0';
syslog(LOG_LOCAL4 | LOG_INFO, "[test] buf is %s, len is %d", buf, strlen(b
uf));
if(strcmp(buf, "start") == 0)
system("/usr/sbin/named -u named -c /etc/named.conf");
if(strcmp(buf, "stop") == 0)
system("killall -9 named");
if(strcmp(buf, "restart") == 0)
system("killall -HUP named");
}else
exit(-1);
}
//exit(0);
}
// parent process
close(clientfd);
}
//return 0;
}
此博客展示了一段C语言代码,通过socket编程实现网络通信。创建socket并绑定地址,监听客户端连接。根据客户端发送的消息,如“start”“stop”“restart”,使用system函数执行相应的系统命令,如启动、停止和重启named服务。
1万+

被折叠的 条评论
为什么被折叠?



