23,188
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <arpa/inet.h>
#include <syslog.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFLEN 128
#define QLEN 10
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 128
#endif
int initserver(int ,struct sockaddr * ,socklen_t ,int );
void server(int sockfd);
void set_cloexec(int);
int main(int ac,char *av[])
{
struct addrinfo hint, *ailist, *aip;
int err, sockfd, n;
char *host;
struct sockaddr_in *sinp;
const char *addr;
char abuf[INET_ADDRSTRLEN];
if(ac != 1)
{
fprintf(stderr,"ruptimed\n");
exit(1);
}
if((n=sysconf(_SC_HOST_NAME_MAX)) < 0)
n = HOST_NAME_MAX;
if((host=malloc(n)) == NULL)
{
perror("malloc");
exit(1);
}
if(gethostname(host,n) < 0)
{
perror("gethostname");
exit(1);
}
//daemonzie("ruptimed");
memset(&hint,0,sizeof(hint));
hint.ai_flags = AI_PASSIVE;
hint.ai_socktype = SOCK_STREAM;
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
if((err=getaddrinfo(host,"ruptime",&hint,&ailist)) != 0)
{
//syslog(LOG_ERR,"ruptime: getaddrinfo error: %s",gai_strerror(err));
fprintf(stderr,"getaddrinfo : %s\n",gai_strerror(err));
exit(1);
}
for(aip=ailist; aip!=NULL; aip=aip->ai_next)
{
if((sockfd=initserver(SOCK_STREAM,aip->ai_addr,aip->ai_addrlen,QLEN)) >= 0)
{
server(sockfd);
exit(0);
}
}
exit(1);
}
int initserver(int type, struct sockaddr *addr,socklen_t alen,int qlen)
{
int fd;
int err;
if((fd=socket(addr->sa_family,type,0)) < 0)
return -1;
if(bind(fd,addr,alen) < 0)
{
perror("bind");
close(fd);
return -1;
}
if(type==SOCK_STREAM || type==SOCK_SEQPACKET)
{
if(listen(fd,qlen) < 0)
{
close(fd);
return -1;
}
}
return fd;
}
void server(int sockfd)
{
int clfd;
FILE *fp;
char buf[BUFLEN];
set_cloexec(sockfd);
for(;;)
{
if((clfd=accept(sockfd,NULL,NULL)) < 0)
{
syslog(LOG_ERR,"ruptimed: accept error : %s",strerror(errno));
exit(1);
}
set_cloexec(clfd);
if((fp=popen("/usr/bin/uptime","r")) == NULL)
{
sprintf(buf,"error: %s\n",strerror(errno));
send(clfd,buf,strlen(buf),0);
}
else
{
while(fgets(buf,BUFLEN,fp) != NULL)
send(clfd,buf,strlen(buf),0);
pclose(fp);
}
close(clfd);
}
}
void set_cloexec(int sockfd)
{
int val;
val = fcntl(sockfd,F_GETFD);
val |= FD_CLOEXEC;
fcntl(sockfd,F_SETFD,val);
}
bind: Cannot assign requested address
$ ./SR1
family inet type stream protocol tcp
address 183.207.232.253 port 13000
bind: Cannot assign requested address