/************************************************************
*FileName : udp_server.c
*description : 本程序说明了如何建立一个可以接收UDP客户端的UDP
* 服务器。注意:使用网络调试助手要指定服务器的IP与Port.
*version : 1.0
*history : none
*************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char * argv [ ])
{
unsigned short port = 8000;
if (argc > 1)
{
port = atoi(argv[1]);
}
//创建套接字
int sockfd;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
perror("socket");
exit(-1);
}
//填充本服务器的信息
struct sockaddr_in my_addr;
bzero(&my_addr,sizeof my_addr);
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
//绑定本程序要使用的信息
int err_log;
err_log = bind(sockfd,(struct sockaddr *)&my_addr,sizeof my_addr);
if (err_log != 0)
{
perror("bind");
close(sockfd);
exit(-1);
}
printf("receive data...\n");
//接收数据
while (1)
{
int recv_len;
char recv_buf[512] = "";
struct sockaddr_in client_addr;
char cli_ip [INET_ADDRSTRLEN] = "";
socklen_t cliaddr_len = sizeof client_addr;
recv_len = recvfrom(sockfd,recv_buf,sizeof recv_buf,0,(struct sockaddr *)&client_addr,&cliaddr_len);
inet_ntop(AF_INET,&client_addr.sin_addr,cli_ip,INET_ADDRSTRLEN);
printf("\nip:%s,port:%d\n",cli_ip,ntohs(client_addr.sin_port));
printf("data(%d):%s\n",recv_len,recv_buf);
}
}
本程序说明了如何建立一个可以接收UDP客户端数据的UDP 服务器
最新推荐文章于 2022-11-07 16:36:42 发布