1 tcp_connect函数
创建一个TCP函数并连接到一个服务器。
int tcp_connect( const char *host, const char *serv )
{
int sockfd, n;
struct addrinfo hints, *res, *ressave;
bzero( &hints,sizeof( struct addrinfo ) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if( ( n = getaddrinfo( host, serv, &hints, &res ) ) != 0 )
{
printf( " tcp_connect error for %s, %s: %s ", host, serv, gai_strerror( n ) );
exit( 1 );
}
ressave = res;
do{
sockfd = socket( res->ai_family, res->ai_socktype, res->ai_protocol );
if( sockfd < 0 )
continue; // ignore this one
if( connect( sockfd, res->ai_addr, res->ai_addrlen ) == 0 )
break; // success
close( sockfd ); // ignore this one
} while( ( res = res->ai_next ) != NULL );
if( res == NULL ) // errno set from final connect()
{
printf( " tcp_connect error for %s, %s ", host, serv );
exit( 1 );
}
freeaddrinfo( ressave );
return( sockfd );
}
2 tcp_listen函数
int tcp_listen( const char *host, const char *serv, socklen_t *addrlenp )
{
int listenfd, n;
const int on = 1;
struct addrinfo hints, *res, *ressave;
bzero( &hints, sizeof( struct addrinfo ) );
hints.ad_flags = AI_PASSIVE;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if( ( n = getaddrinfo( host, serv, &hints, &res ) ) != 0 )
{
printf( " tcp_listen error for %s, %s: %s ", host, serv, gai_strerror( n ) );
exit( 1 );
}
ressave = res;
do
{
listenfd = socket( res->ai_family, res->ai_socktype, res->ai_protocol );
if( listenfd < 0 )
continue; // error,try next one
setsockopt( listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof( on ) );
if( bind( listenfd, res->ai_addr, res->ai_addrlen ) == 0 )
break; // success
close( listenfd );
} while( ( res = res->ai_net ) != NULL );
if( res == NULL ) // errno from final socket() or bind()
{
printf( " tcp_listen error for %s, %s ", host, serv );
exit( 1 );
}
listen( listenfd, LISTENQ );
if( addrlenp )
*addrlenp = res->ai_addrlen; // return size of protocol address
freeaddrinfo( ressave );
return( listenfd );
}