1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define PORT 3339 int main(void){ char *sendbuf="thanks"; char buf[256]; int s_fd,c_fd; int s_len,c_len; struct sockaddr_in s_addr; struct sockaddr_in c_addr; s_fd=socket(AF_INET,SOCK_STREAM,0); s_addr.sin_family=AF_INET; s_addr.sin_addr.s_addr=htonl(INADDR_ANY); s_addr.sin_port=PORT; s_len=sizeof(s_addr); bind(s_fd,(struct sockaddr *)&s_addr,s_len); listen(s_fd,10); while(true){ printf("please wait a moment!\n"); c_len=sizeof(c_addr); c_fd=accept(s_fd,(struct sockaddr *)&c_addr,(socklen_t *__restrict)&c_len); recv(c_fd,buf,256,0); buf[sizeof(buf)+1]='\0'; printf("receive message:\n %s\n",buf); send(c_fd,sendbuf,sizeof(sendbuf),0); close(c_fd); }; return 0; };
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define PORT 3339 int main(void){ int sockfd,len,newsockfd,len2; struct sockaddr_in addr; char *buf="come on!"; char rebuf[40]; sockfd=socket(AF_INET,SOCK_STREAM,0); addr.sin_family=AF_INET; addr.sin_addr.s_addr=htonl(INADDR_ANY); addr.sin_port=PORT; len=sizeof(addr); newsockfd=connect(sockfd,(struct sockaddr *)&addr,len); if(newsockfd==-1){ return 1; }; len2=sizeof(buf); send(sockfd,buf,len2,0); sleep(10); recv(sockfd,rebuf,256,0); rebuf[sizeof(rebuf)+1]='\0'; printf("receive message:\n%s\n",rebuf); close(sockfd); return 0; };
|