server端:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include <arpa/inet.h>
typedef struct sockaddr* SP;
int main()
{
printf("1.创建socket\n");
int sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(0>sockfd)
{
perror("socket");
return -1;
}
printf("2.准备地址\n");
struct sockaddr_in addr ={};
addr.sin_family=AF_INET;
addr.sin_port=htons(6666);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
socklen_t len = sizeof(addr);
printf("3.绑定socket与地址\n");
if(bind(sockfd,(SP)&addr,len))
{
perror("bind");
return -1;
}
struct sockaddr_in addrcli = {};
char buf[1024] ={};
for(;;)
{
printf("4.接收请求\n");
int ret = recvfrom(sockfd,buf,sizeof(buf),0,(SP)&addrcli,&len);
printf("recv:%s,ip:%s,size:%d\n",buf,inet_ntoa(addrcli.sin_addr),ret);
if(0==strcmp("quit",buf));
{
printf("end");
break;
}
printf("5.响应请求\n");
sendto(sockfd,buf,strlen(buf)+1,0,(SP)&addrcli,len);
}
printf("6.关闭\n");
close(sockfd);
}
client端:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
typedef struct sockaddr* SP;
int main()
{
int sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(0 > sockfd)
{
perror("socket");
return -1;
}
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(6666);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
socklen_t len = sizeof(addr);
char buf[1024] = {};
for(;;)
{
printf(">");
gets(buf);
sendto(sockfd,buf,strlen(buf)+1,0,(SP)&addr,len);
if(0 == strcmp("quit",buf))
{
printf("通信结束!\n");
break;
}
recvfrom(sockfd,buf,sizeof(buf),0,(SP)&addr,&len);
printf("recv:%s\n",buf);
}
close(sockfd);
}