⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 server.c

📁 UNIX下的服务器与客户端程序
💻 C
字号:
/*
*  server.c -- This is server program. Written by hanfi 2003-06-07
*  For *NIX 
*/

#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUF_LEN 255
extern int errno;
int sock,fd;

void sigfun(int signum) {  
	close(sock);  
	exit(0);
}

int main() {  
	/*
	struct hostent* host;  
	struct in_addr inadd;  
	unsigned long lna;  
	host = gethostbyname("172.16.2.98"); //此处地址为主机的IP地址  
	printf("%s %d %d\n",host->h_name,host->h_addrtype,host->h_length);  
	bcopy(host->h_addr,&inadd.s_addr, 4);  
	printf("%s \n", inet_ntoa(inadd));  
	lna = htonl(inet_lnaof(inadd));
	bcopy(&lna, &inadd.s_addr, 4);  
	printf("%s \n", inet_ntoa(inadd));
	*/
	int len, fromlen;
	struct protoent *protos;
	struct hostent *host;
	struct sockaddr_in saddr;
	char buf[BUF_LEN];
	struct sockaddr_in from;
	time_t tim;
	signal(SIGHUP, sigfun);  
	signal(SIGINT, sigfun);  
	printf("running...\n");
	if (fork() == 0) {//子进程  
		if ((fd = open("timelog",O_CREAT|O_APPEND|O_WRONLY, 0644)) == -1) {    
			printf("Open error %d: %s\n",errno, strerror(errno));    
			exit(-1);  
		}  
		close(1);  
		dup(fd);  
		close(2);  
		dup(fd);  
		close(0);  
		close(fd);  
		fromlen = sizeof(from);  
		protos = getprotobyname("udp");  
		if ((host = gethostbyname("172.16.2.82")) == NULL) {//这里可以不直接使用IP地址。    
			printf("gethostbyname error\n");    
			exit(-1);  
		}  
		saddr.sin_family = AF_INET;
		saddr.sin_port = htons(5555);  
		bcopy(host->h_addr, &saddr.sin_addr, host->h_length);
		if ((sock = socket(AF_INET, SOCK_DGRAM, protos->p_proto)) < 0) {    
			printf("socket call error\n");    
			exit(-1);  
		}  
		printf("IP = %s, Port = %d\n", inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));  
		if (bind(sock, (struct sockaddr *)&saddr, sizeof(saddr)) == -1) {    
			printf("%s\n",strerror(errno));    
			exit(-1);  
		}  
		for(;;) {   
			if ((len = recvfrom(sock, buf, BUF_LEN, 0, (struct sockaddr *)&from, &fromlen)) == -1){      
				printf("recvfrom error\n");      
				continue;    
			}    
			if (strcmp(buf,"TJB")!=0) continue;    
			tim = time(NULL);    
			tim = htonl(tim);
			printf("recv quest from %s at %s,cmd is %s \n", inet_ntoa(from.sin_addr),ctime(&tim),buf);    
			sendto(sock, &tim, sizeof(time_t), 0, (struct sockaddr *)&from, fromlen);    
			fflush(stdout);  
		}
	}  
	else 
		exit(0);	//*父进程退出//
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -