本地socket通信
1.server
View Code
20 #include <stdio.h> 21 #include <string.h> 22 #include <stdlib.h> 23 #include <unistd.h> 24 #include <sys/socket.h> 25 #include <sys/un.h> 26 27 #define PATH "./tt" 28 29 int main(int argc ,char *argv[]) 30 { 31 int sockfd = 0; 32 struct sockaddr_un addr; 33 unlink(PATH); 34 addr.sun_family = AF_UNIX; 35 strcpy(addr.sun_path,PATH); 36 37 unsigned int len = strlen(addr.sun_path) + sizeof(addr.sun_family); 38 sockfd = socket(AF_UNIX,SOCK_DGRAM,0); 39 if(sockfd < 0 ) 40 { 41 perror("socket error"); 42 exit(-1); 43 } 44 45 if(bind(sockfd,(struct sockaddr *)&addr,len) < 0) 46 { 47 perror("bind error"); 48 close(sockfd); 49 exit(-1); 50 } 51 printf("Bind is ok\n"); 52 53 while(1) 54 { 55 char recv_buf[20] = ""; 56 recvfrom(sockfd,recv_buf,sizeof(recv_buf),0,(struct sockaddr*)&addr,&len); 57 printf("Recv: %s\n",recv_buf); 58 } 59 return 0; 60 61 }
2.client
View Code
#include <stdio.h> 19 #include <string.h> 20 #include <unistd.h> 21 #include <stdlib.h> 22 #include <sys/socket.h> 23 #include <sys/un.h> 24 25 #define PATH "./tt" 26 27 int main(int argc,char *argv[]) 28 { 29 int sockfd = 0; 30 struct sockaddr_un addr; 31 bzero(&addr,sizeof(addr)); 32 33 addr.sun_family = AF_UNIX; 34 strcpy(addr.sun_path,PATH); 35 36 sockfd = socket(AF_UNIX,SOCK_DGRAM,0); 37 if(sockfd < 0) 38 { 39 perror("socket error"); 40 exit(-1); 41 } 42 43 while(1) 44 { 45 static int counter = 0; 46 char send_buf[20] = ""; 47 counter++; 48 sprintf(send_buf,"Counter is %d",counter); 49 int len = strlen(addr.sun_path)+sizeof(addr.sun_family); 50 sendto(sockfd,send_buf,strlen(send_buf),0,(struct sockaddr*)&addr,len); 51 printf("Send: %s\n",send_buf); 52 sleep(1); 53 } 54 return 0; 55 }
posted on 2013-01-29 12:02 keep_simple 阅读(485) 评论(0) 收藏 举报

浙公网安备 33010602011771号