• 基于UDP的本地通信(客户机):
  • 创建流程:
  • 一、创建数据报式套接字(socket函数):
int sock_fd = socket(AF_UNIX,SOCK_DGRAM,0);if(-1 == sock_fd){perror("socket error");exit(-1);}
  • 二、创建客户机和服务器的本地网络信息结构体并填充客户机和服务器本地网络信息结构体 (struct sockaddr_un):
  • 本地网络信息结构体:
#include struct sockaddr_un {sa_family_t sun_family; //AF_UNIXcharsun_path[108];//pathname};
struct sockaddr_un serveraddr,clientaddr;socklen_t serveraddr_len = sizeof(serveraddr);socklen_t clientaddr_len = sizeof(clientaddr);memset(&serveraddr,0,serveraddr_len);memset(&clientaddr,0,clientaddr_len);serveraddr.sun_family = AF_UNIX;clientaddr.sun_family = AF_UNIX;strcpy(serveraddr.sun_path,"./udpserver");strcpy(clientaddr.sun_path,"./udpclient");
  • 三、客户机绑定数据报式套接字(bind函数):
if(-1 == bind(sock_fd,(struct sockaddr *)&clientaddr,clientaddr_len)){perror("bind error");exit(-1);}
  • 四、客户机端发收数据(sendto函数、recvfrom函数):
memset(buf,0,sizeof(buf));fgets(buf,sizeof(buf),stdin);buf[strlen(buf) - 1] = '\0';int ret1 = sendto(sock_fd,buf,sizeof(buf),0,(struct sockaddr *)&serveraddr,serveraddr_len);if(-1 == ret1){perror("sendto error");exit(-1);}int ret2 = recvfrom(sock_fd,buf,sizeof(buf),0,(struct sockaddr*)&serveraddr,&serveraddr_len);if(-1 == ret2){perror("recvfrom error");exit(-1);}printf("服务器[%s]发来应答消息[%s]\n",serveraddr.sun_path,buf);
  • 五、关闭套接字(close函数):
close(sock_fd);
  • 示例代码:
#include #include #include #include #include #include #include #include #include #include int main(int argc, char const *argv[]){//创建套接字int sock_fd = socket(AF_UNIX,SOCK_DGRAM,0);if(-1 == sock_fd){perror("socket error");exit(-1);}//填充网络信息结构体struct sockaddr_un serveraddr,clientaddr;socklen_t serveraddr_len = sizeof(serveraddr);socklen_t clientaddr_len = sizeof(clientaddr);memset(&serveraddr,0,serveraddr_len);memset(&clientaddr,0,clientaddr_len);serveraddr.sun_family = AF_UNIX;clientaddr.sun_family = AF_UNIX;strcpy(serveraddr.sun_path,"./udpserver");strcpy(clientaddr.sun_path,"./udpclient");//绑定套接字if(-1 == bind(sock_fd,(struct sockaddr *)&clientaddr,clientaddr_len)){perror("bind error");exit(-1);}printf("基于UDP的本地通信客户机启动!!!\n");char buf[128] = {0};//收发数据while(true){memset(buf,0,sizeof(buf));fgets(buf,sizeof(buf),stdin);buf[strlen(buf) - 1] = '\0';int ret1 = sendto(sock_fd,buf,sizeof(buf),0,(struct sockaddr *)&serveraddr,serveraddr_len);if(-1 == ret1){perror("sendto error");exit(-1);}int ret2 = recvfrom(sock_fd,buf,sizeof(buf),0,(struct sockaddr*)&serveraddr,&serveraddr_len);if(-1 == ret2){perror("recvfrom error");exit(-1);}printf("服务器[%s]发来应答消息[%s]\n",serveraddr.sun_path,buf);}//关闭套接字close(sock_fd);return 0;}
  • 运行结果:
基于UDP的本地通信客户机启动!!!hello服务器[./udpserver]发来应答消息[hello---------k]I Love China!!!服务器[./udpserver]发来应答消息[I Love China!!!---------k]miss U服务器[./udpserver]发来应答消息[miss U---------k]
  • 特别注意:
  • strcpy(serveraddr.sun_path,"./udpserver");strcpy(clientaddr.sun_path,"./udpclient");代码段中的udpserver文件udpclient文件套接字文件
  • 如下所示:
srwxrwxr-x 1 linux linux 0 1111 01:18 udpclientsrwxrwxr-x 1 linux linux 0 1111 01:18 udpserver