#include "unp.h"
#include <time.h&gt;

int main(int argc, char **argv)
{
    int listenfd, connfd;
    socklen_t len;
    char buff[MAXLINE];
    time_t ticks;
    strct sockaddr_storage clientaddr;

    if(argc==2)
        listenfd=Tcp_listen(NULL,argv[1],&amp;addrlen);
    else if(argc==3)
        listenfd=Tcp_listen(argv[1], argv[2], &amp;addrlen);
    else 
        err_quit("usage: daytimetcpsrv2 [ <host&gt; ] service or port>");
    
    for(;;)
    {
        len=sizeof(clientaddr);
        connfd=Accept(listenfd, (SA *)&amp;clientaddr, &amp;len);
        printf("connection from %sn", Sock_ntop((SA *)&amp;clientaddr,len));

        ticks=time(NULL);
        snprintf(buff, sizeof(buff), "%.24srn", ctime(&amp;ticks));
        Write(connfd, buff, strlen(buff));

        Close(connfd);
    }

}

Protocolindependent daytime server that uses tcp_listen

udp_client’ Function

Our functions that provide a simpler interface to getaddrinfo change with UDP because we provide one client function that creates an unconnected UDP socket, and another in the next section that creates a connected UDP socket.

#include "unp.h"
int udp_client (const char *hostname, const char *service, struct sockaddr **saptr, socklen_t *lenp);
#include "unp.h"
int udp_client(const char *host, const char *serv, SA *saptr, socklen_t *lenp)
{
    int sockfd, n;
    struct addrinfo, *res, *ressave;

    bzero(&amp;hints, sizeof(struct addrinfo));
    hints.ai_family=AF_UNSPEC;
    hints.ai_socktype=SOCK_DGRAM;
    
    if((n=getaddrinfo(host, serv, &amp;hints, &amp;res))!=0)
        err_quit("udp_client error for %s, %s: %s", host, serv, gai_strerror(n));
    
    ressave=res;

    do
    {
        sockfd=socket(res->ai_family, res->ai_socktype, res->ai_protocol);
        if(sockfd>=0)
            break;
    }while((res=res->ai_next)!=NULL);

    if(res==NULL)
        err_sys("udp_client error for %s, %s", host, serv);
    
    *saptr=Malloc(res->ai_addrlen);
    memcpy(*saptr, res->ai_addr, res->ai_addrlen);
    *lenp=res->ai_addrlen;

    freeaddrinfo(ressave);

    return sockfd;
}

udp_client function: creates an unconnected UDP socket

原文地址:https://blog.csdn.net/myfather103/article/details/82724436

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_47584.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注