UDPserver.c
#include<myhead.h>
#define SERPORT 6660
#define SERIP "192.168.0.116"
int main(int argc, const char *argv[])
{
//1、创建套接字
int oldfd = socket(AF_INET,SOCK_DGRAM,0);//para1:ipv4,para2:udp
if(oldfd == -1)
{
perror("socket");
return -1;
}
struct sockaddr_in sin = {
.sin_family = AF_INET,
.sin_port = htons(SERPORT),
.sin_addr.s_addr =inet_addr(SERIP),
};
//2、绑定
if(bind(oldfd,(struct sockaddr *)&sin,sizeof(sin))==-1)
{
perror("绑定失败");
return -1;
}
printf("绑定success");
struct sockaddr_in cin;
socklen_t cinlen = sizeof(cin);
//3、收发消息
char buff[100];
while(1)
{
memset(buff,0,sizeof(buff));
int len =recvfrom(oldfd,buff,sizeof(buff),0,(struct sockaddr *)&cin,&cinlen);//不用管谁发的
//buff[len-1]='\0';
if(strcmp(buff,"mode")==0)
{
connect(oldfd,(struct sockaddr *)&cin,cinlen);
printf("服务器只能与一个客户端通信");
}
if(len==0)
{
perror("客户端跑了");
break;
}
printf("服务器接收到信息%s\n",buff);
// printf("服务器发消息:");
// fgets(buff,sizeof(buff),stdin);
// strcat(buff,"666");
// sendto(oldfd,buff,sizeof(buff),0,(struct sockaddr*)&cin,cinlen);
// printf("发送成功\n");
}
close(oldfd);
return 0;
}
UDPclient
#include<myhead.h>
#define SEVIP "192.168.0.116"
#define SEVPORT 6660
typedef struct sockaddr_in socketaddr;
int main(int argc, const char *argv[])
{
int oldfd=socket(AF_INET,SOCK_DGRAM,0);
if(oldfd == -1)
{
perror("socket");
return -1;
}
in_addr_t port_t = htons(SEVPORT);
in_addr_t ip_t = inet_addr(SEVIP);
socketaddr cln = {
.sin_family = AF_INET,
.sin_port = port_t,
.sin_addr.s_addr = ip_t };
int clnlen = sizeof(cln);
char buff[1024]="";
while(1)
{
printf("客户端发送给服务端:");
fgets(buff,sizeof(buff),stdin);
buff[strlen(buff)-1]='\0';
sendto(oldfd,buff,sizeof(buff),0,(struct sockaddr*)&cln,clnlen);
}
return 0;
}