0

I have been trying to create a program that sends multiple packets via sendto to different IP addresses, but after exactly 1238 callings to sendto I'm getting the error: "SendTo: Invalid argument" (printed by perror). Edit: After an hour the number of callings to sendto is exactly 1231 and remains like that every run. After I added a code that prints something on the screen, it was back to 1238 callings every run until error, deleted that code, it became 1241 and about an hour later it's 1231. If I take down the IP addresses (making the aliases offline), it sends those packets correctly without an error but it get stuck for a moment after about every 500 sendto callings,

This error only happens when those IP addresses are not in the same server, when they are in the same server (aliases) the sendto works correctly. Also, the error doesn't appear when sending to the same IP multiple times instead of multiple times to different IP addresses.

I have tried different fixes that I found when searching in Google. I have tried playing with the configurations in sysctl.conf file, raised the send buffer, somaxconn, backlog, and other things.. When I raised the send buffer, I have also raised the buffer in the application itself.

Here is the sample code I have written: http://pastebin.com/FCn0ALzn

And the code that gives the error:

for (size_t i = 0; i < ips.size(); i++)
    {
        cout << i << ") Sending message to: " << ips[i] << endl;
        server.sin_addr.s_addr = inet_addr(ips[i].c_str());
        n = sendto(sock, buffer, strlen(buffer), 0, (const struct sockaddr *)&server, length);
        if (n < 0)
        {
            perror("Sendto");
            return;
        }
    }
Ben Peretz
  • 49
  • 4
  • 2
    Put the code in the question. And read about why [`while (!file.eof())` is wrong](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – molbdnilo Jan 15 '17 at 10:27
  • Are you sure `ips[i].c_str()` returns a valid IP address, and you're not passing some string to `inet_addr()` that it cannot parse after 1238 calls ? – nos Jan 15 '17 at 11:13
  • I have printed the output of `ips[i].c_str()` and the output of `server.sin_addr` using inet_ntoa, they both printed the correct IP. – Ben Peretz Jan 15 '17 at 11:26

1 Answers1

0

I have managed to fix this issue by clearing IP addresses from the ARP cache. Every 500 callings to sendto, the program sleeps for few milliseconds and then clears the IP addresses that were processed from the ARP cache using the shell command: arp -d [ip] like this:

// Clear ARP cache
void clearIpArp(char* ip)
{
    char arp[100] = {0};
    sprintf(arp, "arp -d %s", ip);
    system(arp);
}
Ben Peretz
  • 49
  • 4