#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define BUFSIZE 64
#define PORT 8888
#define IP “0.0.0.0”
int main(int argc, char *argv[])
{
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if(-1 == fd)
{
perror(“socket”);
exit(-1);
}
//设置自己的IP PORT
struct sockaddr_in sddr, cin;
sddr.sin_family = AF_INET;
sddr.sin_port = htons(PORT);
sddr.sin_addr.s_addr = inet_addr(IP);
socklen_t len = sizeof(cin);
//绑定IP PORT
if(-1 == bind(fd, (void *)&sddr, sizeof(sddr)))
{
perror("bind");
exit(-1);
}
char buf[BUFSIZE];
while(1)
{
if(-1 == recvfrom(fd, buf, BUFSIZE, 0, (void *)&cin, &len))
{
perror("recvfrom");
continue;
}
printf("客户端: IP->%s PORT->%d 发来的消息->%s\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), buf);
if(!strcasecmp(buf, "quit\n"))
{
printf("客户端: IP->%s PORT->%d 退出\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port));
}
}
return 0;
}