当前位置:   article > 正文

C语言 AF_UNIX tcp/udp socket实例_udp af unix

udp af unix

========================udp 方式==========================

udp方式:

服务器端:

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <sys/socket.h>
  6. #include <sys/un.h>
  7. #define PATH "./tt"
  8. int main(int argc ,char *argv[])
  9. {
  10. int sockfd = 0;
  11. struct sockaddr_un addr;
  12. unlink(PATH);
  13. addr.sun_family = AF_UNIX;
  14. strcpy(addr.sun_path,PATH);
  15. unsigned int len = strlen(addr.sun_path) + sizeof(addr.sun_family);
  16. sockfd = socket(AF_UNIX,SOCK_DGRAM,0);
  17. if(sockfd < 0 )
  18. {
  19. perror("socket error");
  20. exit(-1);
  21. }
  22. if(bind(sockfd,(struct sockaddr *)&addr,len) < 0)
  23. {
  24. perror("bind error");
  25. close(sockfd);
  26. exit(-1);
  27. }
  28. printf("Bind is ok\n");
  29. while(1)
  30. {
  31. char recv_buf[20] = "";
  32. recvfrom(sockfd,recv_buf,sizeof(recv_buf),0,(struct sockaddr*)&addr,&len);
  33. printf("Recv: %s\n",recv_buf);
  34. }
  35. return 0;
  36. }

client端:

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <sys/socket.h>
  6. #include <sys/un.h>
  7. #define PATH "./tt"
  8. int main(int argc,char *argv[])
  9. {
  10. int sockfd = 0;
  11. struct sockaddr_un addr;
  12. bzero(&addr,sizeof(addr));
  13. addr.sun_family = AF_UNIX;
  14. strcpy(addr.sun_path,PATH);
  15. sockfd = socket(AF_UNIX,SOCK_DGRAM,0);
  16. if(sockfd < 0)
  17. {
  18. perror("socket error");
  19. exit(-1);
  20. }
  21. while(1)
  22. {
  23. static int counter = 0;
  24. char send_buf[20] = "";
  25. counter++;
  26. sprintf(send_buf,"Counter is %d",counter);
  27. int len = strlen(addr.sun_path)+sizeof(addr.sun_family);
  28. sendto(sockfd,send_buf,strlen(send_buf),0,(struct sockaddr*)&addr,len);
  29. printf("Send: %s\n",send_buf);
  30. sleep(1);
  31. }
  32. return 0;
  33. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/158811
推荐阅读
相关标签
  

闽ICP备14008679号