#include #include #include #include #include char hello[] = "hello socket"; char buf[2048]; int main( int argc, char *argv[] ) { int iFd, ret; socklen_t fromlen; short port = 15678; struct sockaddr_in addr, from; if((iFd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("create socket"); exit( 0 ); } addr.sin_family = AF_INET; addr.sin_port = htons( port ); addr.sin_addr.s_addr = htonl( INADDR_LOOPBACK ); if (bind( iFd, (struct sockaddr *)&addr, sizeof( addr ) ) < 0) { fprintf(stderr,"bind to %d failed %s\n",port,strerror(errno)); exit( 0 ); } shutdown( iFd, 0 ); // shutdown receive // addr.sin_addr.s_addr = htonl( INADDR_LOOPBACK ); if( sendto( iFd, hello, sizeof( hello ), 0, (struct sockaddr *)&addr, sizeof( addr ) ) < 0 ) { perror("sendto"); exit( 0 ); } ret = recvfrom( iFd, buf, sizeof( buf ), 0, (struct sockaddr *)&from, &fromlen ); if( ret < 0 ) { perror("recvfrom"); exit( 0 ); } printf( "received %d bytes [%s]\n", ret, buf ); shutdown( iFd, 1 ); // shutdown send if( sendto( iFd, hello, sizeof( hello ), 0, (struct sockaddr *)&addr, sizeof( addr ) ) < 0 ) { perror("sendto"); exit( 0 ); } return 0; }