7
Send data using TCP
- /*
- * Sends a string to tcp echo server and prints what it returns.
- *
- * socket - PF_INET SOCK_STREAM IPPROTO_UDP
- * htonl
- * connect
- * write
- * read
- * shutdown
- *
- * struct sockaddr_in
- */
- #include <sys/types.h>
- #include <sys/socket.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_STREAM, IPPROTO_TCP )) == -1 )
- goto error;
- sd_address.sin_family = AF_INET;
- sd_address.sin_addr.s_addr = htonl( HOSTADDR );
- sd_address.sin_port = htons( PORTNUM );
- if ( connect( sd, (struct sockaddr *) &sd_address, addrlen ) == -1 )
- goto error;
- if ( write( sd, msg, strlen( msg ) + 1 ) == -1 )
- goto error;
- if ( read( sd, reply, sizeof (reply) ) == -1 )
- goto error;
- if ( shutdown( sd, 2 ) == -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