[YBA] When does write to UDP socket block?

[YBA] When does write to UDP socket block?

Jonathan Ben Avraham yba at tkos.co.il
Wed Mar 7 07:27:47 IST 2012


Hi linux-il colleagues,
In >= 2.6.31 are there any conditions under which a write to a connected 
UDP socket can block? e.g. some change in routing or iface config after 
connect and before write? Has anyone encountered a concrete exampe of a 
write to a UDP socket that blocks? See test code below. That is, I am 
trying to demonstrate that I can get to a situation where UDP write in 
fact does block.
Best regards,

  - yba


#include <stdio.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <net/if.h>
#include <stdlib.h>
#include <errno.h>


int main()
{
         int sd;
         int rc;
         struct ifreq interface;
         struct sockaddr_in sin;
         unsigned char buf[1024];
         struct sockaddr_in  serveraddr;

         if (0 > (sd = socket(AF_INET, SOCK_DGRAM, 0))) {
                 printf("socket failed\n");
                 exit(1);
         }

         sin.sin_family = AF_INET;
         sin.sin_port = htons(0);
         bzero(&(sin.sin_zero), 8);

         sin.sin_addr.s_addr = INADDR_ANY;

         if (-1 == bind(sd, (struct sockaddr *)&sin, sizeof(struct sockaddr_in))) {
                 printf("bind to sd failed [%m]");
                 return -1;
         }


         bzero(&serveraddr, sizeof(struct sockaddr_in));
         serveraddr.sin_family = AF_INET;
         serveraddr.sin_port = htons(80);
         inet_pton(AF_INET, "1.0.1.2", &serveraddr.sin_addr);

         if (0 > (rc = connect(sd, (const struct sockaddr*)&serveraddr, sizeof(serveraddr)))) {
                 printf("connect failed [%m]");
                 exit(1);
         }

         while ( 1 ) {
                 if (0 > (rc = write(sd, buf, 1024))) {
                         printf("write error [%m]\n");
                 }
                 else
                         printf("wrote to socket [%d]\n", rc);
         }
}


-- 
  EE 77 7F 30 4A 64 2E C5  83 5F E7 49 A6 82 29 BA    ~. .~   Tk Open Systems
=}------------------------------------------------ooO--U--Ooo------------{=
      - yba at tkos.co.il - tel: +972.2.679.5364, http://www.tkos.co.il -



More information about the Linux-il mailing list