服务端:
#include<stdio.h>
#include<time.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#define LISTENQ 1024
#define SA struct sockaddr
#define MAXLINE 4096
int main(int argc,char **argv){
int listenfd,connfd;
struct sockaddr_in servaddr;
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,(SA*)&servaddr,sizeof(servaddr));
listen(listenfd,LISTENQ);
for( ; ;){
connfd=accept(listenfd,(SA*)NULL,NULL);
ticks=time(NULL);
snprintf(buff,sizeof(buff),"%.24s\r\n",ctime(&ticks));
write(connfd,buff,strlen(buff));
close(connfd);
}
}
客户端:
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<netinet/in.h>
#define SA struct sockaddr
#define MAXLINE 2048
int main(int argc,char * *argv){
int sockfd,n;
char recvline[MAXLINE+1];
struct sockaddr_in servaddr;
if(argc!=2)printf("usage:a.out<IPaddress>");
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)printf("socket error");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port =htons(13); //datime server
if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr)<=0)printf("inet_pton error for %s",argv[1]);
if(connect(sockfd,(SA *)&servaddr,sizeof(servaddr))<0)printf("connect error");
while((n=read(sockfd,recvline,MAXLINE))>0){
recvline[n]=0; //null terminate
if(fputs(recvline,stdout)==EOF)printf("fputs error");
}
if(n<0)printf("read error");
exit(0);
}
注意事项:root权限 ,先客户端,再服务端