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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
|
int selecting (int fd)
{
struct timeval tv;
tv.tv_sec =0;
tv.tv_usec = rnd(50000,1000000);
fd_set readset;
FD_ZERO(&readset);
FD_SET(fd, &readset);
int err = select(fd + 1, &readset, NULL, NULL, &tv);
std::cout << err << "\n";
if (err <1)
return 0;
if (FD_ISSET(fd,&readset))
return 1;
return 0;
}
...
int main()
...
case 6:
{
if(!filename.empty())
{
time_t start, now;
time(&start);
double elapsedtime = 0;
char *recvbuf;
char *sendbuf;
recvbuf = new char[1024];
sendbuf = new char[1024];
int recvfd, sendfd,err, port;
int errormarker = 0;
if((recvfd = socket(AF_INET,SOCK_DGRAM,0)) == -1)
{
std::cout << "Error setting socket\n";
errormarker =1;
}
if(errormarker ==1)
break;
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(50001);
for (int i =0; i<=9;i++)
{
port = 50001+i;
errormarker = bind(recvfd,(sockaddr*) &server_address, sizeof (server_address));
if(errormarker ==-1)
server_address.sin_port = htons(server_address.sin_port+1);
else
break;
}
if(errormarker == -1)
{
std::cout << "all ports are used, please wait a minute and try again\n";
break;
}
std::cout << "Searching for other musicdata owners\n";
fd_set readset;
while (elapsedtime < 15)
{
if(errormarker != 0)
break;
memset(recvbuf, 0, sizeof(recvbuf));
memset(sendbuf, 0, sizeof(sendbuf));
if (selecting(recvfd))
{
int result = recvfrom(recvfd, recvbuf, 1024, NULL,NULL,NULL);
if (result != -1)
{
buftofile(recvbuf,filename);
addnewdata(filename);
std::cout << "ARE YOU HERE?\n";
}
else
std::cout << "error receiving data \n";
}
filetobuf(sendbuf,filename);
for(int i = 50001; i<=50010;i++)
{
struct addrinfo hints, *servinfo, *p;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype =SOCK_DGRAM;
std::string s_port = to_string(i);
err = getaddrinfo(NULL,s_port.c_str(),&hints,&servinfo);
for(p=servinfo;p!=NULL;p=p->ai_next)
{
if(i == port)
{
err = sendto(recvfd, sendbuf,strlen(sendbuf), 0, p->ai_addr,p->ai_addrlen);
continue;
}
if((sendfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1)
{
continue;
}
else
{
err=sendto(sendfd,sendbuf,strlen(sendbuf), 0, p->ai_addr,p->ai_addrlen);
close(sendfd);
}
}
freeaddrinfo(servinfo);
}
time(&now);
elapsedtime=difftime(now,start);
}
close(recvfd);
}
else
std::cout << "Error, please choose a file to save your data first!" << std::endl;
}
break;
|