sever.c
#include<myhead.h>
#define SERIP "192.168.0.138"
#define SERPORT 8888
int main(int argc, const char *argv[])
{
//1.socket
int oldsocket = socket(AF_INET,SOCK_DGRAM,0);
if(oldsocket == -1)
{
perror("oldsocket");
return -1;
}
//2. bind
struct sockaddr_in sln =
{
.sin_family = AF_INET,
.sin_port = htons(SERPORT),
.sin_addr = inet_addr(SERIP)
};
if(bind(oldsocket,(struct sockaddr*)&sln,sizeof(sln))==-1)
{
perror("bind");
return -1;
}
//3.recvfrom
char buff[1024];
while(1)
{
memset(buff,0,sizeof(buff));
int len = recvfrom(oldsocket,buff,sizeof(buff),0,NULL,NULL);
if(len == 0)
{
printf("客户端跑路\n");
break;
}
printf("客户端发来信息:%s",buff);
}
close(oldsocket);
return 0;
}
client.c
#include<myhead.h>
#define SERIP "192.168.0.138"
#define SERPORT 8888
int main(int argc, const char *argv[])
{
//1.socket
int oldsocket = socket(AF_INET,SOCK_DGRAM,0);
if(oldsocket == -1)
{
perror("oldsocket");
return -1;
}
//2.sendto
struct sockaddr_in cln =
{
.sin_family = AF_INET,
.sin_port = htons(SERPORT),
.sin_addr = inet_addr(SERIP)
};
char buff[1024];
while(1)
{
printf("客户端发去:");
fgets(buff,sizeof(buff),stdin);
sendto(oldsocket,buff,sizeof(buff),0,(struct sockaddr*)&cln,sizeof(cln));
}
close(oldsocket);
return 0;
}