UDP协议实现客服端
步骤:
- 创建套接字
- 指明接收方的地址
- 发送消息
- 关闭消息
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
int main(int argc,char *argv[]){
//创建套接字
int sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd>0)
printf("sockfd=%d\n",sockfd);
else
printf("创建失败\n");
//指明接收方地址
//填充地址结构体
char *des_ip="10.9.71.163";
struct sockaddr_in des_addr;
bzero(&des_addr,sizeof(des_addr));
des_addr.sin_family=AF_INET;
des_addr.sin_port=htons(8000);
inet_pton(AF_INET,des_ip,(void *)&des_addr.sin_addr);
//发送数据
sendto(sockfd,"how are you",sizeof("how are you"),0,(struct sockaddr *)&des_addr, sizeof(des_addr));
//关闭套接字
close(sockfd);
return 0;
}