/******************************************************************************
* *
* udp_server.c *
* *
******************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#define PORT 8888
#define MSG_SIZE 128
int main()
{
int sockfd;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
char buffer[MSG_SIZE];
int addrlen;
int n;
/* 1.创建套接字 */
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
/* 2.1设置地址 */
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
/* 2.2绑定地址 */
bind(sockfd,(struct sockaddr *)&server_addr,
sizeof(struct sockaddr));
/* 3.接收数据 */
while(1)
{
addrlen = sizeof(struct sockaddr);
bzero(buffer, sizeof(buffer));
n = recvfrom(sockfd, buffer, MSG_SIZE, 0, (struct sockaddr *)&client_addr,&addrlen);
buffer[n] = 0;
printf("Server received: %s\n", buffer);
}
/* 4.关闭套接字 */
close(sockfd);
return 0;
}
/******************************************************************************
* *
* udp_client.c *
* *
******************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUF_SIZE 128
#define PORT 8888
int main(int argc, char *argv[])
{
int sockfd;
char buffer[128];
struct sockaddr_in server_addr;
if(argc != 2)
{
printf("Usage: %s server_ip\n",argv[0]);
exit(1);
}
/* 1.创建套接字 */
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
/* 初始化服务器的地址 */
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
inet_aton(argv[1],&server_addr.sin_addr);
while(1)
{
printf("Please input char: \n");
fgets(buffer, BUF_SIZE, stdin);
/* 2.发送数据 */
sendto(sockfd, buffer, strlen(buffer), 0,(struct sockaddr *)&server_addr, sizeof(struct sockaddr));
bzero(buffer, BUF_SIZE);
}
/* 3.关闭套接字 */
close(sockfd);
return 0;
}