#include <myhead.h>
#define SERPORT 8888
#define SERIP "192.168.0.178"
int main(int argc, const char *argv[])
{
int oldfd = socket(AF_INET,SOCK_DGRAM,0);
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)
};
if(bind(oldfd,(struct sockaddr *)&sin,sizeof(sin))==-1)
{
perror("bind");
return -1;
}
struct sockaddr_in cin;
socklen_t cinlen = sizeof(cin);
char buff[1024];
while(1)
{
memset(buff, 0, sizeof(buff));
int len = recvfrom(oldfd, buff, sizeof(buff), 0, (struct sockaddr *)&cin, &cinlen);
if(len == -1)
{
perror("recvfrom");
continue;
}
printf("服务器接收到的消息:%s\n", buff);
// 使用connect函数连接到客户端
if(connect(oldfd, (struct sockaddr *)&cin, cinlen) == -1)
{
perror("connect");
continue;
}
printf("与客户端 %s:%d 建立连接\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port));
// 使用send函数发送响应
strcat(buff, " - 服务器已收到");
if(send(oldfd, buff, strlen(buff), 0) == -1)
{
perror("send");
break;
}
while(1)
{
memset(buff,0,sizeof(buff));
int len = recvfrom(oldfd,buff,sizeof(buff),0,(struct sockaddr *)&cin, &cinlen);
if(len == 0)
{
perror("error");
break;
}
printf("服务器接收到的消息:%s\n",buff);
}
close(oldfd);
return 0;
}
}
09-02
1337
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-31
1921
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-30