简体   繁体   中英

How to correctly reuse a socket for sending UDP packets?

I have a function that gets called each time I want to send a UDP packet.

Things work great if I take these steps:

  1. Create the socket
  2. Set the socket options
  3. Send the packet
  4. Close the socket

However, I don't want to incur the overhead of constantly creating the socket each time the function is called.

Is there a preferred way to handle this? I only want to create the socket once, then keep re-using it. I've tried doing this by introducing a "first_time" flag - but when I take this approach, the sendto() function starts failing with an errno 0x23 .

Since I'm working in VxWorks - it's unclear to me whether this error code is ENOTSUP (VxWorks Error Code) or EWOULDBLOCK (sendto error code). Either way, I'm not what the fix is.

See my code below.


/* Global Scope */
int send_socket = 0;
int first_time = 1;

void myFunction(...)
{
  if (first_time == 1)
  {
    first_time = 0;
    send_socket = socket(PF_INET , SOCK_RAW , IPPROTO_UDP);
    if(send_socket < 0)
        perror("socket() error");

    /* Inform the kernel do not fill up the packet structure. */
    /* We will build our own... */      
    if(setsockopt(send_socket, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0)
      perror("setsockopt() error");
  }

  //  ... populate buffer ...

  if(sendto(send_socket, 
            *buffer, 
            my_ip_header->total_length, 
            0, 
            (struct sockaddr *)&sin, 
            sizeof(sin)) < 0)
  {
    perror("sendto error");
  }

  // Normally I'd close the socket right here...
  // But I don't want to do this, because I want to use it later!
  // close(send_socket);
}

You use raw socket, not the UDP as you stated. Try to use SOCK_DGRAM flag when creating the socket.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM