Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include<unistd.h>
- #include<stdlib.h>
- #include<stdio.h>
- #include<arpa/inet.h>
- #define QUE_LEN 10
- void error(const char *msg){
- perror(msg);
- exit(1);
- }
- void SendServer_char(char *buf,int my_socket,struct sockaddr *server_addr){
- if(sendto(my_socket,buf,1,0,server_addr,sizeof(*server_addr))<0){
- error("send");
- }
- }
- void remove_el(char *arr,int i){
- arr[i++]=0;
- for(;arr[i];i++){
- arr[i-1]=arr[i];
- }
- }
- typedef struct{
- char name[32];
- char password[32];
- struct sockaddr addr;
- } User;
- int main(int argc,char *argv[]){
- int my_socket;
- my_socket=socket(AF_INET,SOCK_STREAM,0);
- int opt=1;
- setsockopt(my_socket,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
- if(my_socket<0){
- error("mysocket");
- }
- /*создали сокет сервера*/
- struct sockaddr_in socket_addr;
- socket_addr.sin_family=AF_INET;
- socket_addr.sin_port=htons(12345);
- socket_addr.sin_addr.s_addr=htons(INADDR_ANY);
- /*заполнили структуру адреса*/
- if(bind(my_socket,(struct sockaddr*)&socket_addr,sizeof(socket_addr))<0){
- error("bind");
- }
- struct sockaddr klient_addr;
- socklen_t size=(socklen_t)sizeof(klient_addr);
- if(listen(my_socket,10)==-1){
- error("listen");
- }
- char *klient_fd=calloc(100,sizeof(char));
- fd_set readfd,writefd;
- int s=0;
- while(1){
- int maxfd=my_socket;
- FD_ZERO(&readfd);
- FD_ZERO(&writefd);
- FD_SET(my_socket,&readfd);
- for(int i=0;klient_fd[i];i++){
- FD_SET(klient_fd[i],&readfd);
- if(maxfd<klient_fd[i]){
- maxfd=klient_fd[i];
- }
- }
- int res=select(maxfd+1,&readfd,NULL,NULL,NULL);
- if(res<1){
- error("select");
- }
- if(FD_ISSET(my_socket,&readfd)){
- struct sockaddr addr;
- klient_fd[s++]=accept(my_socket,&addr,&size);
- }
- for(int i=0;klient_fd[i];i++){
- if(FD_ISSET(klient_fd[i],&readfd)){
- User user;
- read(klient_fd[i],&user,sizeof(user));
- printf("%s %s\n",user.name,user.password);
- remove_el(klient_fd,i);
- s=0;
- }
- }
- }
- /*read(sock,buf,6);*/
- /*printf("%s\n",buf);*/
- /*close(my_socket);*/
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement