效果就像开晚会的表白墙或者上墙一样,多个udp客户端都可以给服务端发送消息。
服务端代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int main(int argc, char** argv)
{
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock < 0)
{
perror("socket");
return 1;
}
//bind
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons(atoi(argv[2]));
local.sin_addr.s_addr = inet_addr(argv[1]);
if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0 )
{
perror("bind");
return 2;
}
char buf[1024];
struct sockaddr_in remote;
socklen_t len = sizeof(remote);
while(1)
{
ssize_t s = recvfrom(sock, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&remote, &len);
if(s > 0)
{
buf[s] = 0;
printf("client %