udp_server
#include<stdio.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#define portnum 3333
void main()
{
int n,addrlen;
char buffer[128];
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int sockfd;
//1创建套接字
sockfd=socket(AF_INET,SOCK_DGRAM,0)
//2.1设置地址
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET; //IPV4协议族
server_addr.sin_port=htons(portnum);
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
//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,128,0,(struct sockaddr *)(&client_addr),&addrlen);
buffer[n]=0; //0是字符串的结束符
printf("server received :%s
",buffer);
}
//4结束连接
close(sockfd);
}
udp_client
#include<stdio.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#define portnum 3333
#define BUF_SIZE 128
int main(int argc, char **argv)
{
char buffer[BUF_SIZE];
struct sockaddr_in server_addr;
int sockfd;
if(argc!=2)
{
printf("usage:%s server_ip
",argv[0]);
exit(1);
}
//1创建套接字
sockfd=socket(AF_INET,SOCK_DGRAM,0)
//2.1设置地址
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET; //IPV4协议族
server_addr.sin_port=htons(portnum);
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
inet_aton(argv[1],&server_addr.sin_addr);
//2发送数据
while(1)
{
printf("please input char:
");
fgets(buffer,128,stdin);
sendto(sockfd,buffer,strlen(buffer),0, (struct sockaddr *)(&server_addr),sizeof(struct sockaddr));
bzero(buffer,sizeof(buffer));
}
//3关闭连接
close(sockfd);
return 0;
}