当前访客身份:游客 [ 登录 | 加入 OSCHINA ]

代码分享

当前位置:
代码分享 » C/C++  » 网络编程
分享到: 
收藏 +0
1
在Linux下写了个小的socket程序,分为客户端和服务器端,服务端开一个端口(2000),做为一个daemon,等待客户的连接请求.一旦有客 户连接,服务器端打印出客户端的IP地址和端口,并且向服务器端发送欢迎信息和时间.下面是服务端的代码(tcpserver.c).由于这只是个简单的 程序,所以只用了单线程实现!

代码片段(2) [全屏查看所有代码]

1. [代码]tcpserver.c     跳至 [1] [2] [全屏预览]

/**
 * Tcp Server program, It is a simple example only.
 * zhengsh 200520602061 2
 * when client connect to server, send a welcome message and timestamp in server.
 */ 

#include  <stdio.h> 
#include  <sys/socket.h> 
#include  <unistd.h> 
#include  <sys/types.h> 
#include  <netinet/in.h> 
#include  <stdlib.h> 
#include  <time.h> 
 
#define  SERVER_PORT 20000  //  define the defualt connect port id 
#define  LENGTH_OF_LISTEN_QUEUE 10  // length of listen queue in server 
#define  BUFFER_SIZE 255 
#define  WELCOME_MESSAGE "welcome to connect the server. " 

int main(int argc, char** argv)
{
       int  servfd,clifd;
       struct  sockaddr_in servaddr,cliaddr;

       if  ((servfd  =  socket(AF_INET,SOCK_STREAM, 0 ))  <   0 )
         {
              printf( " create socket error!\n " );
              exit( 1 );
       } 
 
       bzero( & servaddr, sizeof (servaddr));

       servaddr.sin_family  =  AF_INET;
       servaddr.sin_port  =  htons(SERVER_PORT);
       servaddr.sin_addr.s_addr  =  htons(INADDR_ANY);

       if  (bind(servfd,( struct  sockaddr * ) & servaddr, sizeof (servaddr)) < 0 )
         {
              printf( " bind to port %d failure!\n " ,SERVER_PORT);
              exit( 1 );
       } 
 
        if  (listen(servfd,LENGTH_OF_LISTEN_QUEUE)  <   0 )
         {
              printf( " call listen failure!\n " );
              exit( 1 );
       } 
 
        while  ( 1 )
         { // server loop will nerver exit unless any body kill the process 

              char  buf[BUFFER_SIZE];
              long  timestamp;
              socklen_t length  =   sizeof (cliaddr);
              clifd  =  accept(servfd,( struct  sockaddr * ) & cliaddr, & length);

               if  (clifd  <   0 )
                {
                     printf( " error comes when call accept!\n " );
                     break ;
              } 
 
              strcpy(buf,WELCOME_MESSAGE);

               // inet_ntop(INET_ADDRSTRLEN,cliaddr.sin_addr,buf,BUFFER_SIZE); 

              printf( " from client,IP:%s,Port:%d\n " ,
                 inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));

              timestamp  =  time(NULL);

              strcat(buf, " timestamp in server: " );
              strcat(buf,ctime( & timestamp));

              send(clifd,buf,BUFFER_SIZE, 0 );

              close(clifd);           

       } // exit 
 
       close(servfd);

       return   0 ;
}

2. [代码]tcpclient.c     跳至 [1] [2] [全屏预览]

/**
 * Tcp client program, It is a simple example only.
 * zhengsh 200520602061 2
 * connect to server, and echo a message from server.
 */ 


#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h> 


#define  SERVER_PORT 20000  //  define the defualt connect port id 
#define  CLIENT_PORT ((20001+rand())%65536)  //  define the defualt client port as a random port 
#define  BUFFER_SIZE 255 
#define  REUQEST_MESSAGE "welcome to connect the server.\n" 


void  usage(char* name)
{
       printf( " usage: %s IpAddr\n " ,name);
}


int  main(int argc, char** argv)
{
       int  servfd,clifd,length = 0;
       struct  sockaddr_in servaddr,cliaddr;
       socklen_t socklen  =   sizeof (servaddr);
       char  buf[BUFFER_SIZE];

        if (argc < 2 )
         {
              usage(argv[ 0 ]);
              exit( 1 );
       } 

       if ((clifd  =  socket(AF_INET,SOCK_STREAM, 0 ))  <   0 )
         {
             printf( " create socket error!\n " );
             exit( 1 );
       } 
 
       srand(time(NULL)); // initialize random generator 
 
       bzero( & cliaddr, sizeof (cliaddr));
       cliaddr.sin_family  =  AF_INET;
       cliaddr.sin_port  =  htons(CLIENT_PORT);
       cliaddr.sin_addr.s_addr  =  htons(INADDR_ANY);

       bzero( & servaddr, sizeof (servaddr));
       servaddr.sin_family  =  AF_INET;
       inet_aton(argv[ 1 ], & servaddr.sin_addr);
       servaddr.sin_port  =  htons(SERVER_PORT);
      // servaddr.sin_addr.s_addr = htons(INADDR_ANY); 

       if  (bind(clifd, (struct sockaddr* ) &cliaddr, sizeof (cliaddr)) < 0 )
       {
              printf( " bind to port %d failure!\n " ,CLIENT_PORT);
              exit( 1 );
       } 

        if (connect(clifd,( struct  sockaddr * ) & servaddr, socklen)  <   0 )
       {
              printf( " can't connect to %s!\n ", argv[ 1 ]);
              exit( 1 );
       } 

       length  =  recv(clifd, buf, BUFFER_SIZE, 0);
        if  (length < 0)
        {
              printf( " error comes when recieve data from server %s! ", argv[1] );
              exit( 1 );
       } 

       printf( " from server %s :\n\t%s", argv[1], buf);

       close(clifd);
       return 0;
} 


开源中国-程序员在线工具:Git代码托管 API文档大全(120+) JS在线编辑演示 二维码 更多»

发表评论 回到顶部 网友评论(8)

  • 1楼:ifsc01 发表于 2011-03-19 23:19 回复此评论
    最近在看linux系统编程,还没看到网络编程
  • 2楼:金玉清 发表于 2012-03-04 23:07 回复此评论
    48    
    49        bzero( & cliaddr, sizeof (cliaddr));
    50        cliaddr.sin_family  =  AF_INET;
    51        cliaddr.sin_port  =  htons(CLIENT_PORT);
    52        cliaddr.sin_addr.s_addr  =  htons(INADDR_ANY);
    53   
    你这是在做什么啊?客户端有必要绑定吗?
  • 3楼:家肥猫 发表于 2012-05-07 16:56 回复此评论
    为什么 连不上服务端?
  • 4楼:韩延庆 发表于 2012-06-12 11:08 回复此评论
    123
  • 5楼:Willson_LEE 发表于 2013-09-24 21:04 回复此评论
    客户端不用绑定吧 内核会自己选择源IP和端口的
  • 6楼:修改性别 发表于 2015-05-15 23:53 回复此评论
     printf(" from client,IP:%s,Port:%d\n ",
                     inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
  • 7楼:修改性别 发表于 2015-05-15 23:56 回复此评论

    如果提示这个错误的话,加入下面的头文件就不会报错了。

    #include <arpa/inet.h>

  • 8楼:修改性别 发表于 2015-05-15 23:58 回复此评论

    gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
    Copyright (C) 2011 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


开源从代码分享开始 分享代码