关闭

UNIX网络编程学习(8)--服务器端显示客户端的IP地址和端口号

标签: unix服务器编程网络nullwrapper
1741人阅读 评论(0) 收藏 举报
分类:
#include	"unp.h"
#include	<time.h>

int
main(int argc, char **argv)
{
	int					listenfd, connfd;
	socklen_t           len;
	struct sockaddr_in	servaddr,cliaddr;
	char				buff[MAXLINE];
	time_t				ticks;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(10086);	/* daytime server */

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	for ( ; ; ) {
	    len=sizeof(cliaddr);
		connfd = Accept(listenfd, (SA *) &cliaddr, &len);

		printf("connection from %s,port %d\n",
                Inet_ntop(AF_INET,&cliaddr.sin_addr,buff,sizeof(buff)),
                ntohs(cliaddr.sin_port));

        ticks = time(NULL);
        snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
        Write(connfd, buff, strlen(buff));

		Close(connfd);
	}
}


其中,包裹函数Inet_ntop为:

//wraplib.c

/*
 * Wrapper functions for our own library functions.
 * Most are included in the source file for the function itself.
 */

#include	"unp.h"

const char *
Inet_ntop(int family, const void *addrptr, char *strptr, size_t len)
{
	const char	*ptr;

	if (strptr == NULL)		/* check for old code */
		err_quit("NULL 3rd argument to inet_ntop");
	if ( (ptr = inet_ntop(family, addrptr, strptr, len)) == NULL)
		err_sys("inet_ntop error");		/* sets errno */
	return(ptr);
}

void
Inet_pton(int family, const char *strptr, void *addrptr)
{
	int		n;

	if ( (n = inet_pton(family, strptr, addrptr)) < 0)
		err_sys("inet_pton error for %s", strptr);	/* errno set */
	else if (n == 0)
		err_quit("inet_pton error for %s", strptr);	/* errno not set */

	/* nothing to return */
}


 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:401312次
    • 积分:5514
    • 等级:
    • 排名:第4961名
    • 原创:142篇
    • 转载:71篇
    • 译文:2篇
    • 评论:120条
    我的新浪微博