本次测试是在Ubuntu14.0.4上面测试的,采用的虚拟机是VMware12.0。这个是我作为Linu学习者写的,所以难免会有许多问题,不成熟的地方望大神指教!
首先给出运行结果示意图,大家感兴趣就去看看,因为是代码所以比较枯燥
下面给出服务器端的程序:
[C] 纯文本查看 复制代码 #include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<time.h>
#include<string.h>
#define PORTNUM 13000
#define HOSTLEN 256
#define oops(msg) {perror(msg);exit(1);}
int main(int agc,char *agv[])
{
struct sockaddr_in saddr;
struct hostent *hp;
char hostname[HOSTLEN];
int sock_id,sock_fd;
FILE *sock_fp;
time_t thetime;
/*
*Step1:ask kernel for a socket
*/
sock_id=socket(PF_INET,SOCK_STREAM,0);
if(sock_id==-1)
{
oops("socket");
}
/*
*Step2: bind address to socket.Adress is host,port
*/
bzero((void*)&saddr,sizeof(saddr));
gethostname(hostname,HOSTLEN);
hp=gethostbyname(hostname);
bcopy((void*)hp->h_addr,(void*)&saddr,hp->h_length);
saddr.sin_port=htons(PORTNUM);
saddr.sin_family=AF_INET;
if(bind(sock_id,(struct sockaddr*)&saddr,sizeof(saddr))!=0)
{
oops("bind");
}
/*
*allow incoming calls with Qsize=1 on socket
*/
if(listen(sock_id,1)!=0)
{
oops("listen");
}
/*
* main loop:accept(),write(),close()
*/
while(1)
{
sock_fd=accept(sock_id,NULL,NULL);
printf("Wow!got a call!\n");
if(sock_fd==-1)
{
oops("accept");
}
sock_fp=fdopen(sock_fd,"w");
if(sock_fp==NULL)
{
oops("fdopen");
}
thetime=time(NULL);
fprintf(sock_fp,"The time here is...");
fprintf(sock_fp,"%s",ctime(&thetime));
fclose(sock_fp);
}
return 0;
}
下面是客户端的程序
[C] 纯文本查看 复制代码 #include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<string.h>
#include<unistd.h>
#define oops(meg) {perror(meg);exit(1);}
int main(int agc,char *agv[])
{
struct sockaddr_in servaddr;
struct hostent *hp;
int sock_id,sock_fd;
char message[BUFSIZ];
int messlen;
/*
*Step1: Get a socket
*/
sock_id=socket(AF_INET,SOCK_STREAM,0);
if(sock_id==-1)
{
oops("socket");
}
/*
Step2: connect the server
*/
bzero(&servaddr ,sizeof(servaddr));
hp=gethostbyname(agv[1]);
if(hp==NULL)
{
oops(agv[1]);
}
bcopy(hp->h_addr,(struct sockaddr *)&servaddr.sin_addr,hp->h_length);
servaddr.sin_port=htons(atoi(agv[2]));
servaddr.sin_family=AF_INET;
if(connect(sock_id,(struct sockaddr*)&servaddr,sizeof(servaddr))!=0)
{
oops("connect");
}
/*
*Step3: transfer data form server
*/
messlen=read(sock_id,message,BUFSIZ);
if(messlen==-1)
{
oops("read");
}
if(write(1,message,messlen)!=messlen)
{
oops("write");
}
close(sock_id);
}
|