socket通讯接口代码
#include
#include
#include
#include
#include
#include
#include
#include
#define MYPORT 3490
#define BACKLOG 10
int main( void )
{
int sockfd, new_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size;
if ( (sockfd = socket( AF_INET, SOCK_STREAM, 0 ) ) == -1 )
{
printf( "socket" );
return(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons( MYPORT );
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero( &(my_addr.sin_zero), 10 );
if ( bind( sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr) ) == -1 )
{
printf( "bind" );
return(1);
}
if ( listen( sockfd, BACKLOG ) == -1 )
{
printf( "listen" ); return(1);
}
while ( 1 )
{
sin_size = sizeof(struct sockaddr_in);
if ( (new_fd = accept( sockfd, (struct sockaddr *) &their_addr, &sin_size ) ) == -1 )
{
printf( "accept" );
continue;
}
printf( "server: got connection from %s\n", \
inet_ntoa( their_addr.sin_addr ) );
if ( !fork() )
{
if ( send( new_fd, "Hello, world!\n", 14, 0 ) == -1 )
printf( "send" );
close( new_fd );
exit( 0 );
}
close( new_fd );
while ( waitpid( -1, NULL, WNOHANG ) > 0 )
;
}
}
参考网站:http://www.cnblogs.com/L-hq815/archive/2012/07/09/2583043.html
