UDPClient
/*UDP/IP应用编程接口(API)*/
/*
*客户端的工作流程:首先调用socket函数创建一个Socket,填写服务器地址及端口号,
*从标准输入设备中取得字符串,将字符串传送给服务器端,并接收服务器端返回的字
*符串。最后关闭该socket。
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
int GetServerAddr(char * addrname)
{
printf("please input server addr:");
scanf("%s",addrname);
return 1;
}
int main(int argc,char **argv)
{
int cli_sockfd;
int len;
socklen_t addrlen;
char seraddr[14];
struct sockaddr_in cli_addr;
char buffer[256];
GetServerAddr(seraddr);
/* 建立socket*/
cli_sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(cli_sockfd<0)
{
printf("I cannot socket success\n");
return 1;
}
/* 填写sockaddr_in*/
addrlen=sizeof(struct sockaddr_in);
bzero(&cli_addr,addrlen);
cli_addr.sin_family=AF_INET;
cli_addr.sin_addr.s_addr=inet_addr(seraddr);
//cli_addr.sin_addr.s_addr=htonl(INADDR_ANY);
cli_addr.sin_port=htons(SERVER_PORT);
bzero(buffer,sizeof(buffer));
/* 从标准输入设备取得字符串*/
len=read(STDIN_FILENO,buffer,sizeof(buffer));
/* 将字符串传送给server端*/
sendto(cli_sockfd,buffer,len,0,(struct sockaddr*)&cli_addr,addrlen);
/* 接收server端返回的字符串*/
len=recvfrom(cli_sockfd,buffer,sizeof(buffer),0,(struct sockaddr*)&cli_addr,&addrlen);
//printf("receive from %s\n",inet_ntoa(cli_addr.sin_addr));
printf("receive: %s",buffer);
close(cli_sockfd);
}
UDPServer
/*UDP/IP应用编程接口(API)*/
/*
*服务器的工作流程:首先调用socket函数创建一个Socket,然后调用bind函数将其与本机
*地址以及一个本地端口号绑定,接收到一个客户端时,服务器显示该客户端的IP地址,并将字串
*返回给客户端。
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main(int argc,char **argv)
{
int ser_sockfd;
int len;
//int addrlen;
socklen_t addrlen;
char seraddr[100];
struct sockaddr_in ser_addr;
/*建立socket*/
ser_sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(ser_sockfd<0)
{
printf("I cannot socket success\n");
return 1;
}
/*填写sockaddr_in 结构*/
addrlen=sizeof(struct sockaddr_in);
bzero(&ser_addr,addrlen);
ser_addr.sin_family=AF_INET;
ser_addr.sin_addr.s_addr=htonl(INADDR_ANY);
ser_addr.sin_port=htons(SERVER_PORT);
/*绑定客户端*/
if(bind(ser_sockfd,(struct sockaddr *)&ser_addr,addrlen)<0)
{
printf("connect");
return 1;
}
while(1)
{
bzero(seraddr,sizeof(seraddr));
len=recvfrom(ser_sockfd,seraddr,sizeof(seraddr),0,(struct sockaddr*)&ser_addr,&addrlen);
/*显示client端的网络地址*/
printf("receive from %s\n",inet_ntoa(ser_addr.sin_addr));
/*显示客户端发来的字串*/
printf("recevce:%s",seraddr);
/*将字串返回给client端*/
sendto(ser_sockfd,seraddr,len,0,(struct sockaddr*)&ser_addr,addrlen);
}
}