Link to home
Start Free TrialLog in
Avatar of lwinkenb
lwinkenb

asked on

sendto: Permission denied

Im trying to use sendto to send a UDP packet in my program.  When I try, sendto fails and perror() says "Permission denied".  What is causing this?
Avatar of sunnycoder
sunnycoder
Flag of India image

permission deined error is not thrown by sendto() ... there is no such error listed at its man page ... however, it could be an error due to underlying protocols

make sure that you are not seeing a previously set value of errno and sendto() indeed exits with an error ... If that is the case, then post some code here

PS: If I remember correctly, using raw sockets needs root access, are you using raw sockets ?
Avatar of lwinkenb
lwinkenb

ASKER

here is the code I am using:

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main(int argc, char* argv[])
{
      // Make sure correct number of arguments was passed
      if(argc != 3)
      {
            printf("Usage: udp_send <host> <port>\n");
            return 1;
      }

      int            sock;      // Socket handle
      struct sockaddr_in      serv_addr;      // Server address structure

      // Initialize the structure to 0
      memset(&serv_addr,0,sizeof(struct sockaddr_in));

      // Create the structure
      serv_addr.sin_family = AF_INET;
      serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
      serv_addr.sin_port = htons(atoi(argv[2]));
      // Open the socket
      if((sock = socket(AF_INET,SOCK_DGRAM,0)) < 0)
      {
            perror("client socket()");
            return 1;
      }

      // Read text from stdin in a loop
      char szInput[512];
      int hr = 0;
      while(1)
      {
            scanf("%[^\n]s",szInput);
            if(!strcmp(szInput,".\n"))
            {
                  printf("exiting...\n");
                  break;
            }
            // Send the string
            hr = sendto(sock,szInput,strlen(szInput),0,
                        (struct sockaddr*)&serv_addr,
                        sizeof(struct sockaddr));
            
            if(hr == -1)
            {
                  perror("sendto");
                  return 1;
            }
      }
      return 1;
}

If I run this code on my school computer, it works fine.  When I run it on my home linux server, I get:
sendto: Permission Denied

This happens even when I run it as root.
Just a note for google searchers, I found an answer.  I had to set broadcast permissions for the socket for sendto to work.

int on=1;
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));

ASKER CERTIFIED SOLUTION
Avatar of PashaMod
PashaMod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial