/* UDP Echo Server Author :Andrew Huang */
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h>
#include <stdio.h> #include <string.h>
int main(int argc ,char * argv[]) { unsigned short port = 9000; int sock_fd;
struct sockaddr_in addr; //ipv4的地址结构
struct sockaddr_in client_addr ; socklen_t addr_len;
char buf[1024]; int len ;
if(argc >1) { port = (unsigned short)atoi(argv[1]); }
//第一步:创建一个IPV4,UDP,可以运行所有协议的SOCKET
sock_fd = socket(PF_INET,SOCK_DGRAM,0); if(sock_fd == -1) { perror("socket"); return -1; }
//第二步:用bind来指定端口
memset(&addr,0,sizeof(addr)); addr.sin_port = htons(port); //转成网络序的端口
addr.sin_family = AF_INET; //ipv4的地址类型
//addr.sin_addr.s_addr = inet_addr("0.0.0.0"); //bind 的sin_addr表示在哪一个网卡上有效,
//绑定在0.0.0.0上表示这个SOCKET在所有网卡侦听
addr.sin_addr.s_addr = INADDR_ANY; //INADDR_ANY = 0 = inet_addr("0.0.0.0")
if(bind(sock_fd,(const struct sockaddr *)&addr,sizeof(addr)) == -1) { perror("bind"); close(sock_fd); return -2; }
fprintf(stdout,"UDP Echo Server listen on %d\n",port);
while(1) { memset(&client_addr,0,sizeof(client_addr)); client_addr.sin_family = AF_INET; addr_len = sizeof(client_addr);
len = recvfrom(sock_fd,buf,sizeof(buf),0,(struct sockaddr *)&client_addr,&addr_len);
if(len <=0) continue; buf[len] = 0;
// 以下这种写法表示不关心这个包是从哪里发来,只是接收内容
//len = recvfrom(sock_fd,buf,sizeof(buf),0,NULL,NULL);
fprintf(stdout,"client addr %s ,port %d,buf %s\n",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port),buf);
sendto(sock_fd,buf,len,0,(struct sockaddr *)&client_addr,addr_len);
}
close(sock_fd); }
|