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 69 70 71 72 73 74 75 76 77 78 79 80
| #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include<pthread.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <string.h> #define max_socks 10000 #define buf_size 1000 int* socks[max_socks],now_loc; struct sockaddr_in fsin[max_socks]; void* serve(void* in){ int my_loc=(long)in; int my_sock=*(socks[my_loc]); char* pts=new char[buf_size+1]; while(1){ time_t t = time(NULL); char ch[64] = {0}; char result[100] = {0}; unsigned int tem=fsin[my_loc].sin_addr.s_addr; strftime(ch, sizeof(ch) - 1, "%Y-%m-%d--%H:%M:%S", localtime(&t));
int c1 = sprintf(pts, "\nip: %d.%d.%d.%d port: %u\ntime: %s\nmessage: ", (tem<<24)>>24,(tem<<16)>>24,(tem<<8)>>24,tem>>24,fsin[my_loc].sin_port,ch);
int c2 = recv(my_sock, pts + c1, 1000-c1, 0); pts[c1 + c2] = '\n'; pts[c1+c2+1]='\0'; if(c2==0){ close(my_sock); socks[my_loc]=NULL; break; } printf("%s\n",pts); for(int i=0;i<max_socks;i++){ if(socks[i]!=NULL){ send(*socks[i], pts, strlen(pts), 0); } } } return NULL; }
int main(int argc, char *argv[])
{ pthread_t* thread_handles; thread_handles=(pthread_t*)malloc(max_socks*sizeof(pthread_t)); int msock, ssock; char *service = "50500"; struct sockaddr_in sin; int alen; char pts[1000]; time_t now;
msock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
memset(&sin, '\0', sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons((unsigned short)atoi(service)); bind(msock, (struct sockaddr *)&sin, sizeof(sin));
listen(msock, 5);
while (1) { alen = sizeof(struct sockaddr); ssock = accept(msock, (struct sockaddr *)&fsin[now_loc], (socklen_t *)&alen); socks[now_loc]=new int(ssock); pthread_create(&thread_handles[now_loc],NULL,serve,(void*)now_loc); now_loc++; } close(msock); }
|