linux socket编程示例
Posted 代码如诗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux socket编程示例相关的知识,希望对你有一定的参考价值。
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
static bool stop = false;
static void handle_term( int sig ) // kill pid; in another tty will triggle this signal
{
stop = true;
printf("signal SIGTERM catched...\n");
}
static void handle_int(int sig) // ctrl+c; will triggle this signal
{
printf("signal SIGINT catched...\n");
stop = true;
}
//./listen 127.0.0.1 8888 100
int main( int argc, char* argv[] )
{
signal( SIGTERM, handle_term );
signal(SIGINT, handle_int);
if( argc <= 3 )
{
printf( "usage: %s ip_address port_number backlog\n", basename( argv[0] ) );
return 1;
}
const char* ip = argv[1];
int port = atoi( argv[2] );
int backlog = atoi( argv[3] );
int sock = socket( PF_INET, SOCK_STREAM, 0 );
assert( sock >= 0 );
struct sockaddr_in address;
bzero( &address, sizeof( address ) );
address.sin_family = AF_INET;
inet_pton( AF_INET, ip, &address.sin_addr );
address.sin_port = htons( port );
int ret = bind( sock, ( struct sockaddr* )&address, sizeof( address ) );
assert( ret != -1 );
printf("after bind...\n");
//backlog is the max number of waitting connect in wait queue
ret = listen( sock, backlog ); //listen is a none-block function
assert( ret != -1 );
printf("after listen...\n");
while ( ! stop )
{
sleep( 1 );
}
close( sock );
return 0;
}
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main( int argc, char* argv[] )
{
if( argc <= 2 )
{
printf( "usage: %s ip_address port_number\n", basename( argv[0] ) );
return 1;
}
const char* ip = argv[1];
int port = atoi( argv[2] );
struct sockaddr_in address;
bzero( &address, sizeof( address ) );
address.sin_family = AF_INET;
inet_pton( AF_INET, ip, &address.sin_addr );
address.sin_port = htons( port );
int sock = socket( PF_INET, SOCK_STREAM, 0 );
assert( sock >= 0 );
int ret = bind( sock, ( struct sockaddr* )&address, sizeof( address ) );
assert( ret != -1 );
printf("AFTER bind...\n");
ret = listen( sock, 5 );
assert( ret != -1 );
printf("AFTER listen...\n");
//the returned client is client‘s address
struct sockaddr_in client;
socklen_t client_addrlength = sizeof( client );
int connfd = accept( sock, ( struct sockaddr* )&client, &client_addrlength ); //accept is a block function
printf("AFTER accept...\n");
if ( connfd < 0 )
{
printf( "errno is: %d\n", errno );
}
else
{
//#define INET_ADDRSTRLEN 16 , IPV4 address char array length, <netinet/in.h>
char remote[INET_ADDRSTRLEN ];
printf( "connected with ip: %s and port: %d\n",
inet_ntop( AF_INET, &client.sin_addr, remote, INET_ADDRSTRLEN ), ntohs( client.sin_port ) );
close( connfd );
}
close( sock );
return 0;
}
以上是关于linux socket编程示例的主要内容,如果未能解决你的问题,请参考以下文章