サーバーの並行型通信を行う課題が出たのですが、1部不明点があるので質問します。
コメント(//4)がついている部分のソースコードをどのように書けばよいかわからないので、よろしければ教えてほしいです。
C
1#include<stdio.h> 2#include<stdlib.h> 3#include<string.h> 4#include<unistd.h> 5#include<sys/socket.h> 6#include<netinet/in.h> 7#include<arpa/inet.h> 8#include<sys/types.h> 9#include<pthread.h> 10 11#define BUFSIZE 1024 12#define LISTENQ 1024 13 14void *thread(void *arg); 15 16struct ThreadArgs{ 17 int sock; 18 int cnt; 19 struct sockaddr_in sa; 20}; 21 22int main(int argc,char *argv[]) 23{ 24 int listen_sock,comm_sock,msg_len,sa_len,cnt,n; 25 struct sockaddr_in sa,new_sa; 26 pthread_t thread_id; 27 struct ThreadArgs *args; 28 char buf[BUFSIZE]; 29 30 listen_sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP); 31 32 memset(&sa,0,sizeof(sa)); 33 sa.sin_family = AF_INET; 34 sa.sin_port = htons(49512); 35 sa.sin_addr.s_addr = htonl(INADDR_ANY); 36 37 if(bind(listen_sock,(struct sockaddr*)&sa,sizeof(sa))<0){ 38 fprintf(stderr,"bind()filure\n"); 39 exit(1); 40 } 41 42 if(listen(listen_sock,LISTENQ)<0){ 43 fprintf(stderr,"listen() failure\n"); 44 exit(1); 45 } 46 47 cnt = 0; 48 while(1){ 49 printf("Waiting for a client\n"); 50 sa_len = sizeof(new_sa); 51 if((comm_sock = accept(listen_sock,(struct sockaddr *)&new_sa,&sa_len))<0){ 52 fprintf(stderr,"accept() faiure\n"); 53 exit(1); 54 } 55 56 ++cnt; 57 58 //1 59 args = (struct ThreadArgs *)malloc(sizeof(struct ThreadArgs)); 60 //2 61 args->sock = listen_sock; 62 args->cnt = cnt; 63 args->sa = sa; 64 65 //3 66 if (pthread_create(&thread_id,NULL,(void *)thread,(void *)comm_sock)!=0){ 67 fprintf(stderr,"pthread_create() failure\n"); 68 exit(1); 69} 70 return 0; 71 } 72 73 void *thread(void *arg) 74 { 75 int sock,cnt ,n msg_len; 76 struct sockaddr_in sa; 77 char buf[BUFSIZE]; 78 79 pthread_detach(pthread_self()); 80 81 82 83 //4,argから通信用ソケットディスクリプタ、クライアント番号、アドレス 84 //構造体を取得し、それぞれsock,cnt,saにセット 85 86 87 printf("Client %d(%s)connected\n",cnt,inet_ntoa(sa.sin_addr)); 88 89 if((n = recv(comm_sock,buf,sizeof(buf),0))>0){ 90 buf[n] = '\0'; 91 msg_len = strlen(buf); 92 printf("Client %d:%s\n",cnt,buf); 93 if(send(sock,buf,msg_len,0)!= msg_len){ 94 fprintf(stderr,"send()failure\n"); 95 free(arg); 96 return; 97 98 99 }} 100 close(sock); 101 printf("Client %d disconnected\n",cnt); 102 103 free(arg); 104 105 return; 106 } 107 108
キャストについて調べてみてはいかがでしょうか。
ただ、折角授業料を支払っているのであれば、そこでお聞きするのが一番かと思いますよ。また、ソースはインデントをきちんとわかるようにした方が良いです。