作业要求:
1> 将广播发送端和接收端各实现一遍
2> 将组播发送端和接收端各实现一遍
3> 将流式域套接字的服务器端和客户端各实现一遍
1:将广播发送端和接收端各实现一遍
运行代码:
服务端:
客户端:
运行截图:
2:将组播发送端和接收端各实现一遍
运行代码:
服务端:
客户端:
运行截图:
3:将流式域套接字的服务器端和客户端各实现一遍
运行代码:
服务端:
#include<myhead.h>
int main(int argc, const char *argv[])
{
//1.创建套接字文件
int cfd = socket(AF_UNIX,SOCK_STREAM,0);
if(-1==cfd){
perror("socket error");
return -1;
}
printf("%d success:cfd = %d\n",__LINE__,cfd);
//判断文件是否存在
if(access("./linux",F_OK)==0){
if(unlink("./linux")==-1){
perror("unlink");
return -1;
}
}
//绑定自己
struct sockaddr_un cun;
cun.sun_family = AF_UNIX;
strcpy(cun.sun_path,"./linux");
if(bind(cfd,(struct sockaddr *)&cun,sizeof(cun))==-1){
perror("bind");
return -1;
}
printf("%d success:bind\n",__LINE__);
//请求连接
struct sockaddr_un sun;
sun.sun_family = AF_UNIX;
strcpy(sun.sun_path,"./unix");
if(connect(cfd,(struct sockaddr *)&sun,sizeof(sun))==-1){
perror("connect");
return -1;
}
printf("%d success:connect\n",__LINE__);
//信息交互
char wbuf[128]="";
while(1){
printf("请输入>>>");
fgets(wbuf,sizeof(wbuf)-1,stdin);
wbuf[strlen(wbuf)-1]=0;
send(cfd,wbuf,strlen(wbuf),0);
bzero(wbuf,sizeof(wbuf));
recv(cfd,wbuf,sizeof(wbuf),0);
printf("收到信息>>>%s\n",wbuf);
}
//关闭文件
close(cfd);
return 0;
}
客户端:
#include<myhead.h>
int main(int argc, const char *argv[])
{
//1.创建套接字文件
int sfd = socket(AF_UNIX,SOCK_STREAM,0);
if(-1==sfd){
perror("socket error");
return -1;
}
printf("%d success:sfd = %d\n",__LINE__,sfd);
//2.判断文件是否存在
if(access("./unix",F_OK)==0){
if(unlink("./unix")==-1){
perror("unlink error");
return -1;
}
}
printf("%d success\n",__LINE__);
//3.绑定
struct sockaddr_un sun;
sun.sun_family = AF_UNIX;
strcpy(sun.sun_path,"./unix");
if(-1==bind(sfd,(struct sockaddr *)&sun,sizeof(sun))){
perror("bind error");
return -1;
}
printf("%d success:bind\n",__LINE__);
//4.开启监听模式
if(-1==listen(sfd,128)){
perror("listen error");
return -1;
}
printf("%d success:listen\n",__LINE__);
//5.接受连接
int newfd;
struct sockaddr_un cun;
socklen_t socklen = sizeof(cun);
if(-1 == (newfd = accept(sfd,(struct sockaddr *)&cun,&socklen))){
perror("accept error");
return -1;
}
printf("%d success:accept\n",__LINE__);
printf("[%s] 发来连接请求\n",cun.sun_path);
//6.信息交互
char rbuf[128] = "";
while(1){
bzero(rbuf,sizeof(rbuf));
int res = recv(newfd,rbuf,sizeof(rbuf)-1,0);
if(res<=0){
printf("客户端已下线\n");
return -1;
}
printf("%d [%s]>>>%s\n",__LINE__,cun.sun_path,rbuf);
strcat(rbuf," *<*");
send(newfd,rbuf,strlen(rbuf),0);
//printf("发送成功\n");
}
//7.关闭
close(sfd);
close(newfd);
return 0;
}
运行截图: