#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h>
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #define SER_PORT 3333 int main(int argc, char *argv[]) { if(argc != 2) { printf("Please input server bind ip!\n"); exit(1); } int s_len; int sockfd; int cfd; int n_read; char buffer[1024]; struct sockaddr_in ser_addr; struct sockaddr_in client_addr; if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == - 1) { perror("socket creat error!"); exit(1); } printf("sockfd success!\n"); bzero(&ser_addr,sizeof(ser_addr)); ser_addr.sin_family = AF_INET; //ser_addr.sin_addr.s_addr = htonl(INADDR_ANY); ser_addr.sin_addr.s_addr = inet_addr(argv[1]); ser_addr.sin_port = htons(SER_PORT); if(bind(sockfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr)) == -1) { perror("bind error!"); exit(1); } printf("bind success!\n"); if(listen(sockfd,5) == -1) { perror("listen error!"); exit(1); } printf("listen success!\n"); while(1) { s_len = sizeof(client_addr); if((cfd = accept(sockfd,&client_addr,&s_len)) < 0) { perror("accept error!"); exit(1); } printf("accept success = %s\n",inet_ntoa(client_addr.sin_addr)); n_read = read(cfd,buffer,sizeof(buffer)); buffer[n_read] = '\0'; printf("recv client send msg:%s\n",buffer); } return 0; }
#include <netinet/in.h>#define SER_PORT 3333int main(int argc, char *argv[]){ if(argc != 2) { printf("Please input connect server ip!\n");exit(1); } int sockfd; char buffer[1024]; struct sockaddr_in ser_addr; if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1) { perror("socket create error!");exit(1); } bzero(&ser_addr,sizeof(ser_addr)); ser_addr.sin_family = AF_INET; ser_addr.sin_addr.s_addr = inet_addr(argv[1]); ser_addr.sin_port = htons(SER_PORT); if(connect(sockfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr)) < 0) { perror("connect error!");exit(1); } memset(buffer,0,sizeof(buffer));printf("Please input send msg:\n");gets(buffer);write(sockfd,buffer,strlen(buffer)); return 0;}
socket编程客户端和服务器
最新推荐文章于 2024-03-11 07:00:00 发布