//ser.c
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main()
{
int sockSer = socket(AF_INET, SOCK_DGRAM, 0);
if(sockSer == -1)
{
perror("socket");
exit(1);
}
struct sockaddr_in addrSer;
addrSer.sin_family = AF_INET;
addrSer.sin_port = htons(8080);//端口号
addrSer.sin_addr.s_addr = inet_addr("192.168.1.xx");//服务器地址
socklen_t addrlen = sizeof(struct sockaddr);
int ret = bind(sockSer, (struct sockaddr*)&addrSer, addrlen);
if(ret == -1)
{
perror("bind.");
exit(1);
}
struct sockaddr_in addrCli;
char sendbuf[256];
char recvbuf[256];
while(1)
{
recvfrom(sockSer, recvbuf, 256, 0, (struct sockaddr*)&addrCli, &addrlen);
printf("Cli:>%s\n", recvbuf);
printf("Ser:>");
scanf("%s",sendbuf);
sendto(sockSer, sendbuf, strlen(sendbuf)+1, 0, (struct sockaddr*)&addrCli, addrlen);
}
close(sockSer);
return 0;
}
//cli.c
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main()
{
int sockCli = socket(AF_INET, SOCK_DGRAM, 0);
if(sockCli == -1)
{
perror("socket");
exit(1);
}
struct sockaddr_in addrSer;
addrSer.sin_family = AF_INET;
addrSer.sin_port = htons(8080);//端口号
addrSer.sin_addr.s_addr = inet_addr("192.168.1.xx");//服务器地址
socklen_t addrlen = sizeof(struct sockaddr);
char sendbuf[256];
char recvbuf[256];
while(1)
{
printf("Cli:>");
scanf("%s",sendbuf);
sendto(sockCli, sendbuf, strlen(sendbuf)+1, 0, (struct sockaddr*)&addrSer, addrlen);
recvfrom(sockCli, recvbuf, 256, 0, (struct sockaddr*)&addrSer, &addrlen);
printf("Cli:>%s\n", recvbuf);
}
close(sockCli);
return 0;
}
可实现多个客户端与服务器通讯,客户端端口号和地址必须和服务器一样
但udp模式不像tcp先进行链接,所以必须客户端先发起通讯,让服务器得到客户端的地址,才能进行通讯,而且限制每次发送的次数(客户端一句,服务器一句)还需要改进