[第一版]最简单的发送与接收
server
最大连接数为10,监听13号端口,当有客户端连接上来时,打印客户端的相关信息,同时向客户端发送当前服务器时间
#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(13);
Bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
Listen(listenfd,10);
for(;;){
len=sizeof(cliaddr);
connfd=Accept(listenfd,(struct sockaddr *)&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);
}
}
client
连接到服务端,连接完成后只接受不发送信息,收到第一条信息后打印并退出
#include "unp.h"
int main(int argc,char *argv[]){
int sockfd;
struct sockaddr_in servaddr;
if(argc != 2)
err_quit("usage: client <ip address>");
sockfd=Socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(13);
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
Connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
char buff[1024]={0};
read(sockfd,buff,1024);
printf("received: %s",buff);
exit(0);
}