日期:2014-05-16 浏览次数:20697 次
#include <stdio.h> 2 #include <stdlib.h> 3 #include <sys/types.h> 4 #include <sys/socket.h> 5 #include <string.h> 6 #include <arpa/inet.h> 7 8 9 #define PORT 5000 10 11 12 int main() 13 { 14 int listensfd,connectfd; 15 struct sockaddr_in server; 16 struct sockaddr_in client; 17 int sin_size; 18 19 listensfd = socket(AF_INET,SOCK_STREAM,0); 20 if (listensfd < 0) 21 { 22 perror("socket failed!"); 23 exit(1); } 25 else 26 { 27 printf("Create socket success!\n"); 28 } 29 30 bzero(&server,sizeof(server)); 31 server.sin_family = AF_INET; 32 server.sin_port = htons(PORT); 33 server.sin_addr.s_addr = htonl(INADDR_ANY); 34 if (bind(listensfd,(struct sockaddr *)&server,sizeof(struct sock addr)) == -1) 35 { 36 perror("bind error!"); 37 exit(1); 38 } 39 else 40 { 41 printf("bind success!\n"); 42 } 43 44 if (listen(listensfd,5) < 0) 45 { 46 printf("listen error!"); 47 exit(1); 48 } 49 else 50 { 51 printf("listen success!\n"); 52 } 53 54 sin_size = sizeof(struct sockaddr_in); 55 if ((connectfd = accept(listensfd,(struct sockaddr *)&client,&sin_size)) == -1) 56 { 57 perror("accept error!"); 58 exit(1); } 60 else 61 { 62 printf("asdfsdfsadf"); 63 send(connectfd,"Welcom to my service!",50,0); 64 close(connectfd); 65 close(listensfd); 66 } 67 return 1; 68 }
1 #include <stdio.h> 2 #include <string.h> 3 #include <sys/types.h> 4 #include <sys/socket.h> 5 #include <netinet/in.h> 6 #include <arpa/inet.h> 7 8 9 #define PORT 5000 10 11 int main() 12 { 13 int sockfd; 14 char buf[512]; 15 struct sockaddr_in server; 16 sockfd = socket(AF_INET,SOCK_STREAM,0); 17 if (sockfd < 0) 18 { 19 perror("Create socket failed!\n"); 20 exit(1); 21 } 22 else 23 { 24 printf("Creat socket success!\n"); 25 } 26 bzero(&server,sizeof(server)); 27 server.sin_family = AF_INET; 28 server.sin_port = htons(PORT); 29 inet_aton("127.0.0.1",&server.sin_addr); 30 if (connect(sockfd,(struct sockaddr *)&server,sizeof(struct sockaddr) < 0)) 31 { 32 perror("connect failed!\n"); 33 } 34 else 35 { 36 recv(sockfd,buf,sizeof(buf),0); 37 printf("%s",buf); 38 } 39 }