- 论坛徽章:
- 0
|
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <time.h>
#include <signal.h>
#define CLIENT_PORT 2004
#define SERVER_PORT 20001
#define LENGTH_OF_LISTEN_QUEUE 10
#define BUFFER_SIZE 255
int main(int argc, char **argv)
{
int servfd,clifd,length=0;
struct sockaddr_in servaddr,cliaddr;
char cc[100];
int port;
pid_t pid;
srand(time(NULL));
if ((servfd = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("create socket error!\n");
exit(1);
}
switch (argv[1][0]){
case '0':
port=2001;break;
case '1':
port=2002;break;
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
if(bind(servfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0)
{
printf("bind to port %d failure!\n",port);
exit(1);
}
if(listen(servfd,LENGTH_OF_LISTEN_QUEUE)<0)
{
printf("call listen failure!\n");
exit(1);
}
char c;int i;
do
{
char buf[BUFFER_SIZE];
long timestamp;
socklen_t length = sizeof(cliaddr);
clifd = accept(servfd,(struct sockaddr *)&cliaddr,&length);
if(clifd < 0)
{
printf("error comes when call accept!\n");
break;
}
pid = fork();
switch(pid)
{
default:
while(length = read(clifd,buf,BUFFER_SIZE))
{
sprintf(cc,"\n-------recv message start-------\n");
write(STDOUT_FILENO, cc,strlen(cc));
write(STDOUT_FILENO, buf, length);
//sprintf(cc,"\n%d\n",length);
//write(STDOUT_FILENO, cc, 100);
sprintf(cc,"\n-------recv message end-------\n");
write(STDOUT_FILENO, cc,strlen(cc));
}
kill(pid,SIGKILL);
break;
case 0:
{}
int sockfd;
struct sockaddr_in servaddr2,cliaddr2;
socklen_t socklen2 = sizeof(servaddr);
char buf2[BUFFER_SIZE];
int cp;
cp = CLIENT_PORT+( rand() % 65535 );
if((clifd = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("create socket error!\n");
exit(1);
}
bzero(&cliaddr2,sizeof(cliaddr2));
cliaddr2.sin_family = AF_INET;
cliaddr2.sin_port = htons(cp);
cliaddr2.sin_addr.s_addr =htons(INADDR_ANY);
bzero(&servaddr2,sizeof(servaddr));
servaddr2.sin_family = AF_INET;
inet_aton("127.0.0.1",&servaddr.sin_addr);
servaddr2.sin_port = htons(SERVER_PORT);
int aaa;
if((aaa=bind(sockfd,(struct sockaddr *)&cliaddr2,sizeof(cliaddr2))) < 0)
{
printf("bind to port %d failure!\n",cp);
exit(1);
}
if(connect(sockfd,(struct sockaddr*)&servaddr2,socklen2) < 0)
{
printf("can`t connect to ");
exit(1);
}
while(1){
i = 0;
while( (c = getchar())!='\n'){
buf2=c;
i++;
}
buf2=0;
write(sockfd,buf2,strlen(buf2));
}
break;
}
}while(1);
close(servfd);
return 0;
}
程序在红色部分bind的时候出错了。。。可能是什么原因?不解。。。
[ 本帖最后由 leeews 于 2008-5-22 16:38 编辑 ] |
|