15
Send data in non blocking mode
- /*
- *
- * Sends a string to udp echo server in non blocking mode and prints what it returns.
- *
- * fcntl
- * poll
- * struct fds
- */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <sys/fcntl.h>
- #include <netinet/in.h>
- #include <sys/poll.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <strings.h>
- #include <errno.h>
- #if defined( LINUX )
- #include <string.h>
- #endif
- #include <unistd.h>
- #define TIMEOUT 2*1000 /* in msecs */
- #define HOSTADDR INADDR_LOOPBACK /* 0x7F000001U */
- #define PORTNUM 10007 /* IPPORT_ECHO */
- int main( int argc, char **argv ) {
- int sd = -1;
- struct sockaddr_in sd_address;
- int addrlen = sizeof (struct sockaddr_in);
- struct pollfd ps;
- char *msg = "HELLO";
- char reply[16];
- if ( (sd = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP )) == -1 )
- goto error;
- #if 1
- /* non-blocking io */
- if ( fcntl( sd, F_SETFL, O_NONBLOCK ) == -1 )
- goto error;
- #endif
- sd_address.sin_family = AF_INET;
- sd_address.sin_addr.s_addr = htonl( HOSTADDR );
- sd_address.sin_port = htons( PORTNUM );
- if ( sendto( sd, msg, strlen( msg ) + 1, 0, (struct sockaddr *) &sd_address, addrlen ) == -1 )
- goto error;
- #if 1
- /* block until ready to read */
- ps.fd = sd;
- ps.events = POLLIN;
- switch ( poll( &ps, 1, TIMEOUT ) ) {
- case 0:
- errno = EWOULDBLOCK;
- case -1:
- goto error;
- }
- #endif
- if ( recvfrom( sd, reply, sizeof (reply), 0, 0, 0 ) == -1 )
- goto error;
- close( sd );
- fprintf( stdout, "%s\n", reply );
- exit( 0 );
- error:
- fprintf( stderr, "%s(%i)\n", strerror( errno ), errno );
- if ( sd != -1 )
- close( sd );
- exit( 1 );
- }
Comments