6
Send data using UDP
- /*
- * Sends a string to udp echo server and prints what it returns.
- *
- * socket - PF_INET SOCK_DGRAM IPPROTO_UDP
- * htonl
- * sendto
- * recvfrom
- * strerror
- *
- * struct sockaddr_in
- */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <sys/fcntl.h>
- #include <netinet/in.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <strings.h>
- #include <errno.h>
- #if defined( LINUX )
- #include <string.h>
- #endif
- #include <unistd.h>
- #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);
- char *msg = "HELLO";
- char reply[16];
- if ( (sd = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP )) == -1 )
- goto error;
- 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 ( recvfrom( sd, reply, sizeof (reply), 0, 0, &addrlen ) == -1 )
- goto error;
- close( sd );
- fprintf( stdout, "%s\n", reply );
- exit( 0 );
- error:
- fprintf( stderr, "%s\n", strerror( errno ) );
- if ( sd != -1 )
- close( sd );
- exit( 1 );
- }
Comments