daytime 服务简单示例[0623]

首先,要安装相应的包,daytime 包括被包含在xinetd中

step 1

在终端中输入,sudo apt-get install xinetd 回车

step 2

安装后要简单配置下

sudo gedit /etc/xinetd.d/daytime

我的系统是ubuntu jaunty,其内容如下

# default: off
# description: An internal xinetd service which gets the current system time
# then prints it out in a format like this: "Wed Nov 13 22:30:27 EST 2002".
# This is the tcp version.
service daytime
{
    disable        = yes     <--此处改为no,即可启用tcp形式对应的服务,下面那个为udp的,按需改就行了
    type        = INTERNAL
    id        = daytime-stream
    socket_type    = stream
    protocol    = tcp
    user        = root
    wait        = no
}                                                                               

# This is the udp version.
service daytime
{
    disable        = yes
    type        = INTERNAL
    id        = daytime-dgram
    socket_type    = dgram
    protocol    = udp
    user        = root
    wait        = yes

}        

step 3

重启下xinetd服务

在终端中输入

sudo /etc/init.d/xinetd stop 回车

然后

sudo /etc/init.d/xinetd start 回车

step 4

下面开始编程,

这里给出一个例子

ContractedBlock.gif ExpandedBlockStart.gif Code
#include <stdio.h>
#include 
<netinet/in.h>
#include 
<arpa/inet.h>
#include 
<unistd.h>
#include 
<netdb.h>
 
int main (int argc, char *argv[])
{
    
char *host;
    
int sockfd;
    
int len,result;
    
struct sockaddr_in address;
    
struct hostent *hostinfo;
    
struct servent *servinfo;
    
char buffer[128];
    
if(argc==1)
    {
        host
="localhost";
    }
    
else
    {
        host
=argv[1];
    }
    hostinfo
=gethostbyname(host);
    
if(!hostinfo)
    {
        fprintf(stderr,
"no host:%s\n",host);
        
return(1);
    }
    servinfo
=getservbyname("daytime","tcp");
    
if(!servinfo)
    {
        fprintf(stderr,
"no daytime service\n");
        
return(1);
    }
    printf(
"daytime port is %d\n",ntohs(servinfo->s_port));
    sockfd
=socket(AF_INET,SOCK_STREAM,0);
    address.sin_family
=AF_INET;
    address.sin_addr
=*(struct in_addr *)*hostinfo->h_addr_list;
    
//inet_pton(AF_INET,"127.0.0.1",&address.sin_addr);
        
//上面这行可用来与此之前的两行替换,调用的函数不同而已
    address.sin_port=servinfo->s_port;
    len
=sizeof(address);
    result
=connect(sockfd,(struct sockaddr *)&address,len);
    
if(result==-1)
    {
        perror(
"oops : getdate\n");
        
return(1);
    }

    result
=read(sockfd,buffer,sizeof(buffer));
    buffer[result]
='\0';
    printf(
"read %d bytes :%s\n",result,buffer);
    close(sockfd);
    
return(0);
}

 

 

 

 

转载于:https://www.cnblogs.com/pingf/archive/2009/06/23/1509333.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值