思维导图1、
1、广播服务器代码
#include "head.h"
#define IP "192.168.125.255"
#define PORT 6789
int main(int argc, const char *argv[])
{
int bfd=socket(AF_INET,SOCK_DGRAM,0);
if(bfd==-1){
perror("socket error");
return -1;
}
int basd=1;
if(setsockopt(bfd,SOL_SOCKET,SO_BROADCAST,&basd,sizeof(basd))==-1){
perror("setsockopt error");
return -1;
}
struct sockaddr_in rin;
rin.sin_family=AF_INET;
rin.sin_port=htons(PORT);
rin.sin_addr.s_addr=inet_addr(IP);
char sbuf[128]="";
while(1){
printf("请输入>>>");
fgets(sbuf,sizeof(sbuf),stdin);
sbuf[strlen(sbuf)-1]=0;
sendto(bfd,sbuf,strlen(sbuf),0,(struct sockaddr*)&rin,sizeof(rin));
printf("发送成功\n");
}
close(bfd);
return 0;
}
2、组播客户端代码
#include "head.h"
int main(int argc, const char *argv[])
{
int rfd=socket(AF_INET,SOCK_DGRAM,0);
if(rfd==-1)
{
perror("socket error");
return -1;
}
struct ip_mreqn imq;
imq.imr_multiaddr.s_addr=inet_addr("224.1.1.1");
imq.imr_address.s_addr=inet_addr("192.168.125.71");
imq.imr_ifindex=2;
if(setsockopt(rfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&imq,sizeof(imq))){
perror("setsockopt error");
return -1;
}
printf("加入多播组成功\n");
struct sockaddr_in rin;
rin.sin_family=AF_INET;
rin.sin_port=htons(5555);
rin.sin_addr.s_addr=inet_addr("224.1.1.1");
if(bind(rfd,(struct sockaddr*)&rin,sizeof(rin))==-1){
perror("bind error");
return -1;
}
char rbuf[128]="";
while(1){
bzero(rbuf,sizeof(rbuf));
recvfrom(rfd,rbuf,sizeof(rbuf),0,NULL,NULL);
printf("收到组播消息:%s\n",rbuf);
}
close(rfd);
return 0;
}
作业1、控制机械臂
#include "head.h"
#define SET_IP "192.168.125.48"
#define SET_PORT 8888
#define CLI_IP "192.168.125.71"
#define CLI_PORT 5555
int main(int argc, const char *argv[])
{
int bfd=socket(AF_INET,SOCK_STREAM,0);
if(bfd==-1){
perror("socket error");
return -1;
}
int reuse=1;
if(setsockopt(bfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
{
perror("setsockopt error");
return -1;
}
printf("端口号快速重启成功\n");
struct sockaddr_in cin;
cin.sin_family=AF_INET;
cin.sin_port=htons(CLI_PORT);
cin.sin_addr.s_addr=inet_addr(CLI_IP);
if(bind(bfd,(struct sockaddr*)&cin,sizeof(cin))==-1){
perror("bind error");
return -1;
}
printf("bind success\n");
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(SET_PORT);
sin.sin_addr.s_addr=inet_addr(SET_IP);
if(connect(bfd,(struct sockaddr*)&sin,sizeof(sin))==-1){
perror("connect error");
return -1;
}
printf("connect success\n");
char rbuf[5]={0xff,0x02,0x00,0x10,0xff};
unsigned char bbuf[5]={0xff,0x02,0x01,0x10,0xff};
char kong;
printf("请输入一个指令:");
while(1){
scanf("%c",&kong);
while(getchar()!=10);
switch(kong){
case 'w':rbuf[3]++;break;
case 's':rbuf[3]--;break;
case 'd':bbuf[3]++;break;
case 'a':bbuf[3]--;break;
default:
break;
}
send(bfd,rbuf,sizeof(rbuf),0);
send(bfd,bbuf,sizeof(bbuf),0);
}
close(bfd);
return 0;
}
作业2、基于UDP的TFTP文件传输