- 论坛徽章:
- 0
|
使用bcopy和bzero的疑问???
int main() {
int s, ns, len; //sockets id
char messhead[10]; //message head
char *member;
char hostname[HOSTLEN];
struct hostent *hp;
struct sockaddr_in coaddr;
struct sockaddr_in praddr;
if ((s= socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket" ;
exit(1);
}
gethostname(hostname,sizeof(hostname));
if((hp = gethostbyname(hostname)) == NULL) {
fprintf(stderr, "unknown host %s\n", hostname);
exit(1);
}
bzero(&coaddr, sizeof(coaddr));
coaddr.sin_family = AF_INET;
coaddr.sin_port = htons(PORTA);
bcopy(hp->;h_addr, &coaddr.sin_addr, hp->;h_length);
len = sizeof(coaddr);
if(bind(s, (struct sockaddr *) &coaddr, len) < 0) {
perror("binding socket" ;
exit(1);
}
if(listen(s, MAXMEMBERS) < 0) {
perror("listen" ;
exit(1);
}
while(1) {
bzero(&praddr, sizeof(praddr)); l en = sizeof(praddr);
if((ns = accept(s, (struct sockaddr *) &praddr, &len) ) < 0 ) {
perror("accepting connection" ;
exit(1);
}
if(fork() == 0) { //child process
while(1) {
for(i=0; i<=MAXLEN; i++) inbuf='\0';
for(i=0; i<10; i++) messhead='\0';
recv(ns, inbuf,MAXLEN,0);
sscanf(inbuf, "%s", messhead);
printf("receive: %s\n", messhead);
if(strcmp(messhead,"MESS" == 0) {
}
if(strcmp(messhead,"JOIN" == 0) {
//do join
sendback( ns);
sendadd();
}
if(strcmp(messhead,"LEAVE" == 0) {
sendleave(ns);
printf("Leave finish!\n" ;
//close(ns);
}
}
}
}
}
int sendadd() {
struct sockaddr_in member;
struct hostent *nhp;
char gmname[MAXMEMBERS][HOSTLEN];
int s; //socket ID
char host[HOSTLEN];
int n=0;
//read member list from file
memberlist=fopen(filename, "r" ;
while((fgets(host, HOSTLEN, memberlist))!=NULL) {
strcpy(gmname[n++], host);
}
fclose(memberlist);
//distributed add hostname to others
for(i=0; i<(n-1); i++) {
printf("in distributed hostname function 1\n" ;
bzero(nhp, sizeof(nhp));
if((nhp=gethostbyname(gmname)) <0) {
perror("unknown hostname");
return(-1);
}
printf("in distributed hostname function 2\n");
if((s = socket(AF_INET, SOCK_STREAM, 0))<0) {
perror("sendchange");
return(-1);
}
printf("in distributed hostname function 3\n");
bzero(&member, sizeof(member));
member.sin_family = AF_INET;
member.sin_port = htons(PORTB);
bcopy(nhp->;h_addr, &member.sin_addr, nhp->;h_length);
printf("in distributed hostname function 4\n");
if(connect(s, (struct sockaddr *) &member, sizeof(member)) <0) {
perror("distribut IPs failed");
return(-1);
}
printf("in distributed hostname function 5 \n");
send(s, "ADD", MAXLEN, 0);
printf("send add to client!\n");
for(i=0; i<=MAXLEN; i++) outbuf='\0';
strcpy(outbuf, gmname[n-1]);
send(s, outbuf, MAXLEN, 0);
close(s);
}
printf("function sendadd finish!\n");
return(1);
}
程序大体就是这个结构,还有函数我没有贴出来。为什么在mian函数里好好的, 在下面一个自定义函数就不行了? |
|